es6.js 5.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. /** @hidden */
  414. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  415. // Rebuild shaders source code
  416. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  417. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  418. vertexCode = prefix + vertexCode;
  419. fragmentCode = prefix + fragmentCode;
  420. // Number lines of shaders source code
  421. var i = 2;
  422. var regex = /\n/gm;
  423. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  424. i = 2;
  425. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  426. // Dump shaders name and formatted source code
  427. if (this.name.vertexElement) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  430. }
  431. else if (this.name.vertex) {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  434. }
  435. else {
  436. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  437. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  438. }
  439. };
  440. ;
  441. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  442. var preparedSourceCode = this._processPrecision(sourceCode);
  443. if (this._engine.webGLVersion == 1) {
  444. callback(preparedSourceCode);
  445. return;
  446. }
  447. // Already converted
  448. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  449. callback(preparedSourceCode.replace("#version 300 es", ""));
  450. return;
  451. }
  452. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  453. // Remove extensions
  454. // #extension GL_OES_standard_derivatives : enable
  455. // #extension GL_EXT_shader_texture_lod : enable
  456. // #extension GL_EXT_frag_depth : enable
  457. // #extension GL_EXT_draw_buffers : require
  458. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  459. var result = preparedSourceCode.replace(regex, "");
  460. // Migrate to GLSL v300
  461. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  462. result = result.replace(/attribute[ \t]/g, "in ");
  463. result = result.replace(/[ \t]attribute/g, " in");
  464. if (isFragment) {
  465. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  467. result = result.replace(/texture2D\s*\(/g, "texture(");
  468. result = result.replace(/textureCube\s*\(/g, "texture(");
  469. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  470. result = result.replace(/gl_FragColor/g, "glFragColor");
  471. result = result.replace(/gl_FragData/g, "glFragData");
  472. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  473. }
  474. callback(result);
  475. };
  476. Effect.prototype._processIncludes = function (sourceCode, callback) {
  477. var _this = this;
  478. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  479. var match = regex.exec(sourceCode);
  480. var returnValue = new String(sourceCode);
  481. while (match != null) {
  482. var includeFile = match[1];
  483. // Uniform declaration
  484. if (includeFile.indexOf("__decl__") !== -1) {
  485. includeFile = includeFile.replace(/__decl__/, "");
  486. if (this._engine.supportsUniformBuffers) {
  487. includeFile = includeFile.replace(/Vertex/, "Ubo");
  488. includeFile = includeFile.replace(/Fragment/, "Ubo");
  489. }
  490. includeFile = includeFile + "Declaration";
  491. }
  492. if (Effect.IncludesShadersStore[includeFile]) {
  493. // Substitution
  494. var includeContent = Effect.IncludesShadersStore[includeFile];
  495. if (match[2]) {
  496. var splits = match[3].split(",");
  497. for (var index = 0; index < splits.length; index += 2) {
  498. var source = new RegExp(splits[index], "g");
  499. var dest = splits[index + 1];
  500. includeContent = includeContent.replace(source, dest);
  501. }
  502. }
  503. if (match[4]) {
  504. var indexString = match[5];
  505. if (indexString.indexOf("..") !== -1) {
  506. var indexSplits = indexString.split("..");
  507. var minIndex = parseInt(indexSplits[0]);
  508. var maxIndex = parseInt(indexSplits[1]);
  509. var sourceIncludeContent = includeContent.slice(0);
  510. includeContent = "";
  511. if (isNaN(maxIndex)) {
  512. maxIndex = this._indexParameters[indexSplits[1]];
  513. }
  514. for (var i = minIndex; i < maxIndex; i++) {
  515. if (!this._engine.supportsUniformBuffers) {
  516. // Ubo replacement
  517. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  518. return p1 + "{X}";
  519. });
  520. }
  521. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  522. }
  523. }
  524. else {
  525. if (!this._engine.supportsUniformBuffers) {
  526. // Ubo replacement
  527. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  528. return p1 + "{X}";
  529. });
  530. }
  531. includeContent = includeContent.replace(/\{X\}/g, indexString);
  532. }
  533. }
  534. // Replace
  535. returnValue = returnValue.replace(match[0], includeContent);
  536. }
  537. else {
  538. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  539. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  540. Effect.IncludesShadersStore[includeFile] = fileContent;
  541. _this._processIncludes(returnValue, callback);
  542. });
  543. return;
  544. }
  545. match = regex.exec(sourceCode);
  546. }
  547. callback(returnValue);
  548. };
  549. Effect.prototype._processPrecision = function (source) {
  550. if (source.indexOf("precision highp float") === -1) {
  551. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  552. source = "precision mediump float;\n" + source;
  553. }
  554. else {
  555. source = "precision highp float;\n" + source;
  556. }
  557. }
  558. else {
  559. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  560. source = source.replace("precision highp float", "precision mediump float");
  561. }
  562. }
  563. return source;
  564. };
  565. /**
  566. * Recompiles the webGL program
  567. * @param vertexSourceCode The source code for the vertex shader.
  568. * @param fragmentSourceCode The source code for the fragment shader.
  569. * @param onCompiled Callback called when completed.
  570. * @param onError Callback called on error.
  571. */
  572. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  573. var _this = this;
  574. this._isReady = false;
  575. this._vertexSourceCodeOverride = vertexSourceCode;
  576. this._fragmentSourceCodeOverride = fragmentSourceCode;
  577. this.onError = function (effect, error) {
  578. if (onError) {
  579. onError(error);
  580. }
  581. };
  582. this.onCompiled = function () {
  583. var scenes = _this.getEngine().scenes;
  584. for (var i = 0; i < scenes.length; i++) {
  585. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  586. }
  587. if (onCompiled) {
  588. onCompiled(_this._program);
  589. }
  590. };
  591. this._fallbacks = null;
  592. this._prepareEffect();
  593. };
  594. /**
  595. * Gets the uniform locations of the the specified variable names
  596. * @param names THe names of the variables to lookup.
  597. * @returns Array of locations in the same order as variable names.
  598. */
  599. Effect.prototype.getSpecificUniformLocations = function (names) {
  600. var engine = this._engine;
  601. return engine.getUniforms(this._program, names);
  602. };
  603. /**
  604. * Prepares the effect
  605. */
  606. Effect.prototype._prepareEffect = function () {
  607. var attributesNames = this._attributesNames;
  608. var defines = this.defines;
  609. var fallbacks = this._fallbacks;
  610. this._valueCache = {};
  611. var previousProgram = this._program;
  612. try {
  613. var engine = this._engine;
  614. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  615. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  616. }
  617. else {
  618. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  619. }
  620. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  621. if (engine.supportsUniformBuffers) {
  622. for (var name in this._uniformBuffersNames) {
  623. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  624. }
  625. }
  626. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  627. this._attributes = engine.getAttributes(this._program, attributesNames);
  628. var index;
  629. for (index = 0; index < this._samplers.length; index++) {
  630. var sampler = this.getUniform(this._samplers[index]);
  631. if (sampler == null) {
  632. this._samplers.splice(index, 1);
  633. index--;
  634. }
  635. }
  636. engine.bindSamplers(this);
  637. this._compilationError = "";
  638. this._isReady = true;
  639. if (this.onCompiled) {
  640. this.onCompiled(this);
  641. }
  642. this.onCompileObservable.notifyObservers(this);
  643. this.onCompileObservable.clear();
  644. // Unbind mesh reference in fallbacks
  645. if (this._fallbacks) {
  646. this._fallbacks.unBindMesh();
  647. }
  648. if (previousProgram) {
  649. this.getEngine()._deleteProgram(previousProgram);
  650. }
  651. }
  652. catch (e) {
  653. this._compilationError = e.message;
  654. // Let's go through fallbacks then
  655. BABYLON.Tools.Error("Unable to compile effect:");
  656. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  657. return " " + uniform;
  658. }));
  659. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  660. return " " + attribute;
  661. }));
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * This function will add a new shader to the shader store
  1193. * @param name the name of the shader
  1194. * @param pixelShader optional pixel shader content
  1195. * @param vertexShader optional vertex shader content
  1196. */
  1197. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1198. if (pixelShader) {
  1199. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1200. }
  1201. if (vertexShader) {
  1202. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1203. }
  1204. };
  1205. /**
  1206. * Resets the cache of effects.
  1207. */
  1208. Effect.ResetCache = function () {
  1209. Effect._baseCache = {};
  1210. };
  1211. Effect._uniqueIdSeed = 0;
  1212. Effect._baseCache = {};
  1213. /**
  1214. * Store of each shader (The can be looked up using effect.key)
  1215. */
  1216. Effect.ShadersStore = {};
  1217. /**
  1218. * Store of each included file for a shader (The can be looked up using effect.key)
  1219. */
  1220. Effect.IncludesShadersStore = {};
  1221. return Effect;
  1222. }());
  1223. BABYLON.Effect = Effect;
  1224. })(BABYLON || (BABYLON = {}));
  1225. //# sourceMappingURL=babylon.effect.js.map
  1226. //# sourceMappingURL=babylon.types.js.map
  1227. var BABYLON;
  1228. (function (BABYLON) {
  1229. var KeyboardEventTypes = /** @class */ (function () {
  1230. function KeyboardEventTypes() {
  1231. }
  1232. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1233. get: function () {
  1234. return KeyboardEventTypes._KEYDOWN;
  1235. },
  1236. enumerable: true,
  1237. configurable: true
  1238. });
  1239. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1240. get: function () {
  1241. return KeyboardEventTypes._KEYUP;
  1242. },
  1243. enumerable: true,
  1244. configurable: true
  1245. });
  1246. KeyboardEventTypes._KEYDOWN = 0x01;
  1247. KeyboardEventTypes._KEYUP = 0x02;
  1248. return KeyboardEventTypes;
  1249. }());
  1250. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1251. var KeyboardInfo = /** @class */ (function () {
  1252. function KeyboardInfo(type, event) {
  1253. this.type = type;
  1254. this.event = event;
  1255. }
  1256. return KeyboardInfo;
  1257. }());
  1258. BABYLON.KeyboardInfo = KeyboardInfo;
  1259. /**
  1260. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1261. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1262. */
  1263. var KeyboardInfoPre = /** @class */ (function (_super) {
  1264. __extends(KeyboardInfoPre, _super);
  1265. function KeyboardInfoPre(type, event) {
  1266. var _this = _super.call(this, type, event) || this;
  1267. _this.skipOnPointerObservable = false;
  1268. return _this;
  1269. }
  1270. return KeyboardInfoPre;
  1271. }(KeyboardInfo));
  1272. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1273. })(BABYLON || (BABYLON = {}));
  1274. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1275. var BABYLON;
  1276. (function (BABYLON) {
  1277. var PointerEventTypes = /** @class */ (function () {
  1278. function PointerEventTypes() {
  1279. }
  1280. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERDOWN;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERUP;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERMOVE;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERWHEEL;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERPICK;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1316. get: function () {
  1317. return PointerEventTypes._POINTERTAP;
  1318. },
  1319. enumerable: true,
  1320. configurable: true
  1321. });
  1322. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1323. get: function () {
  1324. return PointerEventTypes._POINTERDOUBLETAP;
  1325. },
  1326. enumerable: true,
  1327. configurable: true
  1328. });
  1329. PointerEventTypes._POINTERDOWN = 0x01;
  1330. PointerEventTypes._POINTERUP = 0x02;
  1331. PointerEventTypes._POINTERMOVE = 0x04;
  1332. PointerEventTypes._POINTERWHEEL = 0x08;
  1333. PointerEventTypes._POINTERPICK = 0x10;
  1334. PointerEventTypes._POINTERTAP = 0x20;
  1335. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1336. return PointerEventTypes;
  1337. }());
  1338. BABYLON.PointerEventTypes = PointerEventTypes;
  1339. var PointerInfoBase = /** @class */ (function () {
  1340. function PointerInfoBase(type, event) {
  1341. this.type = type;
  1342. this.event = event;
  1343. }
  1344. return PointerInfoBase;
  1345. }());
  1346. BABYLON.PointerInfoBase = PointerInfoBase;
  1347. /**
  1348. * This class is used to store pointer related info for the onPrePointerObservable event.
  1349. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1350. */
  1351. var PointerInfoPre = /** @class */ (function (_super) {
  1352. __extends(PointerInfoPre, _super);
  1353. function PointerInfoPre(type, event, localX, localY) {
  1354. var _this = _super.call(this, type, event) || this;
  1355. /**
  1356. * Ray from a pointer if availible (eg. 6dof controller)
  1357. */
  1358. _this.ray = null;
  1359. _this.skipOnPointerObservable = false;
  1360. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1361. return _this;
  1362. }
  1363. return PointerInfoPre;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfoPre = PointerInfoPre;
  1366. /**
  1367. * This type contains all the data related to a pointer event in Babylon.js.
  1368. * 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.
  1369. */
  1370. var PointerInfo = /** @class */ (function (_super) {
  1371. __extends(PointerInfo, _super);
  1372. function PointerInfo(type, event, pickInfo) {
  1373. var _this = _super.call(this, type, event) || this;
  1374. _this.pickInfo = pickInfo;
  1375. return _this;
  1376. }
  1377. return PointerInfo;
  1378. }(PointerInfoBase));
  1379. BABYLON.PointerInfo = PointerInfo;
  1380. })(BABYLON || (BABYLON = {}));
  1381. //# sourceMappingURL=babylon.pointerEvents.js.map
  1382. var BABYLON;
  1383. (function (BABYLON) {
  1384. BABYLON.ToGammaSpace = 1 / 2.2;
  1385. BABYLON.ToLinearSpace = 2.2;
  1386. BABYLON.Epsilon = 0.001;
  1387. /**
  1388. * Class used to hold a RBG color
  1389. */
  1390. var Color3 = /** @class */ (function () {
  1391. /**
  1392. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1393. * @param r defines the red component (between 0 and 1, default is 0)
  1394. * @param g defines the green component (between 0 and 1, default is 0)
  1395. * @param b defines the blue component (between 0 and 1, default is 0)
  1396. */
  1397. function Color3(
  1398. /**
  1399. * Defines the red component (between 0 and 1, default is 0)
  1400. */
  1401. r,
  1402. /**
  1403. * Defines the green component (between 0 and 1, default is 0)
  1404. */
  1405. g,
  1406. /**
  1407. * Defines the blue component (between 0 and 1, default is 0)
  1408. */
  1409. b) {
  1410. if (r === void 0) { r = 0; }
  1411. if (g === void 0) { g = 0; }
  1412. if (b === void 0) { b = 0; }
  1413. this.r = r;
  1414. this.g = g;
  1415. this.b = b;
  1416. }
  1417. /**
  1418. * Creates a string with the Color3 current values
  1419. * @returns the string representation of the Color3 object
  1420. */
  1421. Color3.prototype.toString = function () {
  1422. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1423. };
  1424. /**
  1425. * Returns the string "Color3"
  1426. * @returns "Color3"
  1427. */
  1428. Color3.prototype.getClassName = function () {
  1429. return "Color3";
  1430. };
  1431. /**
  1432. * Compute the Color3 hash code
  1433. * @returns an unique number that can be used to hash Color3 objects
  1434. */
  1435. Color3.prototype.getHashCode = function () {
  1436. var hash = this.r || 0;
  1437. hash = (hash * 397) ^ (this.g || 0);
  1438. hash = (hash * 397) ^ (this.b || 0);
  1439. return hash;
  1440. };
  1441. // Operators
  1442. /**
  1443. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1444. * @param array defines the array where to store the r,g,b components
  1445. * @param index defines an optional index in the target array to define where to start storing values
  1446. * @returns the current Color3 object
  1447. */
  1448. Color3.prototype.toArray = function (array, index) {
  1449. if (index === undefined) {
  1450. index = 0;
  1451. }
  1452. array[index] = this.r;
  1453. array[index + 1] = this.g;
  1454. array[index + 2] = this.b;
  1455. return this;
  1456. };
  1457. /**
  1458. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1459. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1460. * @returns a new {BABYLON.Color4} object
  1461. */
  1462. Color3.prototype.toColor4 = function (alpha) {
  1463. if (alpha === void 0) { alpha = 1; }
  1464. return new Color4(this.r, this.g, this.b, alpha);
  1465. };
  1466. /**
  1467. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1468. * @returns the new array
  1469. */
  1470. Color3.prototype.asArray = function () {
  1471. var result = new Array();
  1472. this.toArray(result, 0);
  1473. return result;
  1474. };
  1475. /**
  1476. * Returns the luminance value
  1477. * @returns a float value
  1478. */
  1479. Color3.prototype.toLuminance = function () {
  1480. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1481. };
  1482. /**
  1483. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1484. * @param otherColor defines the second operand
  1485. * @returns the new Color3 object
  1486. */
  1487. Color3.prototype.multiply = function (otherColor) {
  1488. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1489. };
  1490. /**
  1491. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1492. * @param otherColor defines the second operand
  1493. * @param result defines the Color3 object where to store the result
  1494. * @returns the current Color3
  1495. */
  1496. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1497. result.r = this.r * otherColor.r;
  1498. result.g = this.g * otherColor.g;
  1499. result.b = this.b * otherColor.b;
  1500. return this;
  1501. };
  1502. /**
  1503. * Determines equality between Color3 objects
  1504. * @param otherColor defines the second operand
  1505. * @returns true if the rgb values are equal to the given ones
  1506. */
  1507. Color3.prototype.equals = function (otherColor) {
  1508. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1509. };
  1510. /**
  1511. * Determines equality between the current Color3 object and a set of r,b,g values
  1512. * @param r defines the red component to check
  1513. * @param g defines the green component to check
  1514. * @param b defines the blue component to check
  1515. * @returns true if the rgb values are equal to the given ones
  1516. */
  1517. Color3.prototype.equalsFloats = function (r, g, b) {
  1518. return this.r === r && this.g === g && this.b === b;
  1519. };
  1520. /**
  1521. * Multiplies in place each rgb value by scale
  1522. * @param scale defines the scaling factor
  1523. * @returns the updated Color3
  1524. */
  1525. Color3.prototype.scale = function (scale) {
  1526. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1527. };
  1528. /**
  1529. * Multiplies the rgb values by scale and stores the result into "result"
  1530. * @param scale defines the scaling factor
  1531. * @param result defines the Color3 object where to store the result
  1532. * @returns the unmodified current Color3
  1533. */
  1534. Color3.prototype.scaleToRef = function (scale, result) {
  1535. result.r = this.r * scale;
  1536. result.g = this.g * scale;
  1537. result.b = this.b * scale;
  1538. return this;
  1539. };
  1540. /**
  1541. * Scale the current Color3 values by a factor and add the result to a given Color3
  1542. * @param scale defines the scale factor
  1543. * @param result defines color to store the result into
  1544. * @returns the unmodified current Color3
  1545. */
  1546. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1547. result.r += this.r * scale;
  1548. result.g += this.g * scale;
  1549. result.b += this.b * scale;
  1550. return this;
  1551. };
  1552. /**
  1553. * Clamps the rgb values by the min and max values and stores the result into "result"
  1554. * @param min defines minimum clamping value (default is 0)
  1555. * @param max defines maximum clamping value (default is 1)
  1556. * @param result defines color to store the result into
  1557. * @returns the original Color3
  1558. */
  1559. Color3.prototype.clampToRef = function (min, max, result) {
  1560. if (min === void 0) { min = 0; }
  1561. if (max === void 0) { max = 1; }
  1562. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1563. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1564. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1565. return this;
  1566. };
  1567. /**
  1568. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1569. * @param otherColor defines the second operand
  1570. * @returns the new Color3
  1571. */
  1572. Color3.prototype.add = function (otherColor) {
  1573. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1574. };
  1575. /**
  1576. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1577. * @param otherColor defines the second operand
  1578. * @param result defines Color3 object to store the result into
  1579. * @returns the unmodified current Color3
  1580. */
  1581. Color3.prototype.addToRef = function (otherColor, result) {
  1582. result.r = this.r + otherColor.r;
  1583. result.g = this.g + otherColor.g;
  1584. result.b = this.b + otherColor.b;
  1585. return this;
  1586. };
  1587. /**
  1588. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1589. * @param otherColor defines the second operand
  1590. * @returns the new Color3
  1591. */
  1592. Color3.prototype.subtract = function (otherColor) {
  1593. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1594. };
  1595. /**
  1596. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1597. * @param otherColor defines the second operand
  1598. * @param result defines Color3 object to store the result into
  1599. * @returns the unmodified current Color3
  1600. */
  1601. Color3.prototype.subtractToRef = function (otherColor, result) {
  1602. result.r = this.r - otherColor.r;
  1603. result.g = this.g - otherColor.g;
  1604. result.b = this.b - otherColor.b;
  1605. return this;
  1606. };
  1607. /**
  1608. * Copy the current object
  1609. * @returns a new Color3 copied the current one
  1610. */
  1611. Color3.prototype.clone = function () {
  1612. return new Color3(this.r, this.g, this.b);
  1613. };
  1614. /**
  1615. * Copies the rgb values from the source in the current Color3
  1616. * @param source defines the source Color3 object
  1617. * @returns the updated Color3 object
  1618. */
  1619. Color3.prototype.copyFrom = function (source) {
  1620. this.r = source.r;
  1621. this.g = source.g;
  1622. this.b = source.b;
  1623. return this;
  1624. };
  1625. /**
  1626. * Updates the Color3 rgb values from the given floats
  1627. * @param r defines the red component to read from
  1628. * @param g defines the green component to read from
  1629. * @param b defines the blue component to read from
  1630. * @returns the current Color3 object
  1631. */
  1632. Color3.prototype.copyFromFloats = function (r, g, b) {
  1633. this.r = r;
  1634. this.g = g;
  1635. this.b = b;
  1636. return this;
  1637. };
  1638. /**
  1639. * Updates the Color3 rgb values from the given floats
  1640. * @param r defines the red component to read from
  1641. * @param g defines the green component to read from
  1642. * @param b defines the blue component to read from
  1643. * @returns the current Color3 object
  1644. */
  1645. Color3.prototype.set = function (r, g, b) {
  1646. return this.copyFromFloats(r, g, b);
  1647. };
  1648. /**
  1649. * Compute the Color3 hexadecimal code as a string
  1650. * @returns a string containing the hexadecimal representation of the Color3 object
  1651. */
  1652. Color3.prototype.toHexString = function () {
  1653. var intR = (this.r * 255) | 0;
  1654. var intG = (this.g * 255) | 0;
  1655. var intB = (this.b * 255) | 0;
  1656. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1657. };
  1658. /**
  1659. * Computes a new Color3 converted from the current one to linear space
  1660. * @returns a new Color3 object
  1661. */
  1662. Color3.prototype.toLinearSpace = function () {
  1663. var convertedColor = new Color3();
  1664. this.toLinearSpaceToRef(convertedColor);
  1665. return convertedColor;
  1666. };
  1667. /**
  1668. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1669. * @param convertedColor defines the Color3 object where to store the linear space version
  1670. * @returns the unmodified Color3
  1671. */
  1672. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1673. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1674. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1675. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1676. return this;
  1677. };
  1678. /**
  1679. * Computes a new Color3 converted from the current one to gamma space
  1680. * @returns a new Color3 object
  1681. */
  1682. Color3.prototype.toGammaSpace = function () {
  1683. var convertedColor = new Color3();
  1684. this.toGammaSpaceToRef(convertedColor);
  1685. return convertedColor;
  1686. };
  1687. /**
  1688. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1689. * @param convertedColor defines the Color3 object where to store the gamma space version
  1690. * @returns the unmodified Color3
  1691. */
  1692. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1693. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1694. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1695. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1696. return this;
  1697. };
  1698. // Statics
  1699. /**
  1700. * Creates a new Color3 from the string containing valid hexadecimal values
  1701. * @param hex defines a string containing valid hexadecimal values
  1702. * @returns a new Color3 object
  1703. */
  1704. Color3.FromHexString = function (hex) {
  1705. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1706. return new Color3(0, 0, 0);
  1707. }
  1708. var r = parseInt(hex.substring(1, 3), 16);
  1709. var g = parseInt(hex.substring(3, 5), 16);
  1710. var b = parseInt(hex.substring(5, 7), 16);
  1711. return Color3.FromInts(r, g, b);
  1712. };
  1713. /**
  1714. * Creates a new Vector3 from the starting index of the given array
  1715. * @param array defines the source array
  1716. * @param offset defines an offset in the source array
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.FromArray = function (array, offset) {
  1720. if (offset === void 0) { offset = 0; }
  1721. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1722. };
  1723. /**
  1724. * Creates a new Color3 from integer values (< 256)
  1725. * @param r defines the red component to read from (value between 0 and 255)
  1726. * @param g defines the green component to read from (value between 0 and 255)
  1727. * @param b defines the blue component to read from (value between 0 and 255)
  1728. * @returns a new Color3 object
  1729. */
  1730. Color3.FromInts = function (r, g, b) {
  1731. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1732. };
  1733. /**
  1734. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1735. * @param start defines the start Color3 value
  1736. * @param end defines the end Color3 value
  1737. * @param amount defines the gradient value between start and end
  1738. * @returns a new Color3 object
  1739. */
  1740. Color3.Lerp = function (start, end, amount) {
  1741. var r = start.r + ((end.r - start.r) * amount);
  1742. var g = start.g + ((end.g - start.g) * amount);
  1743. var b = start.b + ((end.b - start.b) * amount);
  1744. return new Color3(r, g, b);
  1745. };
  1746. /**
  1747. * Returns a Color3 value containing a red color
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.Red = function () { return new Color3(1, 0, 0); };
  1751. /**
  1752. * Returns a Color3 value containing a green color
  1753. * @returns a new Color3 object
  1754. */
  1755. Color3.Green = function () { return new Color3(0, 1, 0); };
  1756. /**
  1757. * Returns a Color3 value containing a blue color
  1758. * @returns a new Color3 object
  1759. */
  1760. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1761. /**
  1762. * Returns a Color3 value containing a black color
  1763. * @returns a new Color3 object
  1764. */
  1765. Color3.Black = function () { return new Color3(0, 0, 0); };
  1766. /**
  1767. * Returns a Color3 value containing a white color
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.White = function () { return new Color3(1, 1, 1); };
  1771. /**
  1772. * Returns a Color3 value containing a purple color
  1773. * @returns a new Color3 object
  1774. */
  1775. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1776. /**
  1777. * Returns a Color3 value containing a magenta color
  1778. * @returns a new Color3 object
  1779. */
  1780. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1781. /**
  1782. * Returns a Color3 value containing a yellow color
  1783. * @returns a new Color3 object
  1784. */
  1785. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1786. /**
  1787. * Returns a Color3 value containing a gray color
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1791. /**
  1792. * Returns a Color3 value containing a teal color
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1796. /**
  1797. * Returns a Color3 value containing a random color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1801. return Color3;
  1802. }());
  1803. BABYLON.Color3 = Color3;
  1804. /**
  1805. * Class used to hold a RBGA color
  1806. */
  1807. var Color4 = /** @class */ (function () {
  1808. /**
  1809. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1810. * @param r defines the red component (between 0 and 1, default is 0)
  1811. * @param g defines the green component (between 0 and 1, default is 0)
  1812. * @param b defines the blue component (between 0 and 1, default is 0)
  1813. * @param a defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. function Color4(
  1816. /**
  1817. * Defines the red component (between 0 and 1, default is 0)
  1818. */
  1819. r,
  1820. /**
  1821. * Defines the green component (between 0 and 1, default is 0)
  1822. */
  1823. g,
  1824. /**
  1825. * Defines the blue component (between 0 and 1, default is 0)
  1826. */
  1827. b,
  1828. /**
  1829. * Defines the alpha component (between 0 and 1, default is 1)
  1830. */
  1831. a) {
  1832. if (r === void 0) { r = 0; }
  1833. if (g === void 0) { g = 0; }
  1834. if (b === void 0) { b = 0; }
  1835. if (a === void 0) { a = 1; }
  1836. this.r = r;
  1837. this.g = g;
  1838. this.b = b;
  1839. this.a = a;
  1840. }
  1841. // Operators
  1842. /**
  1843. * Adds in place the given Color4 values to the current Color4 object
  1844. * @param right defines the second operand
  1845. * @returns the current updated Color4 object
  1846. */
  1847. Color4.prototype.addInPlace = function (right) {
  1848. this.r += right.r;
  1849. this.g += right.g;
  1850. this.b += right.b;
  1851. this.a += right.a;
  1852. return this;
  1853. };
  1854. /**
  1855. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1856. * @returns the new array
  1857. */
  1858. Color4.prototype.asArray = function () {
  1859. var result = new Array();
  1860. this.toArray(result, 0);
  1861. return result;
  1862. };
  1863. /**
  1864. * Stores from the starting index in the given array the Color4 successive values
  1865. * @param array defines the array where to store the r,g,b components
  1866. * @param index defines an optional index in the target array to define where to start storing values
  1867. * @returns the current Color4 object
  1868. */
  1869. Color4.prototype.toArray = function (array, index) {
  1870. if (index === undefined) {
  1871. index = 0;
  1872. }
  1873. array[index] = this.r;
  1874. array[index + 1] = this.g;
  1875. array[index + 2] = this.b;
  1876. array[index + 3] = this.a;
  1877. return this;
  1878. };
  1879. /**
  1880. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1881. * @param right defines the second operand
  1882. * @returns a new Color4 object
  1883. */
  1884. Color4.prototype.add = function (right) {
  1885. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1886. };
  1887. /**
  1888. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1889. * @param right defines the second operand
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.subtract = function (right) {
  1893. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1894. };
  1895. /**
  1896. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1897. * @param right defines the second operand
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current Color4 object
  1900. */
  1901. Color4.prototype.subtractToRef = function (right, result) {
  1902. result.r = this.r - right.r;
  1903. result.g = this.g - right.g;
  1904. result.b = this.b - right.b;
  1905. result.a = this.a - right.a;
  1906. return this;
  1907. };
  1908. /**
  1909. * Creates a new Color4 with the current Color4 values multiplied by scale
  1910. * @param scale defines the scaling factor to apply
  1911. * @returns a new Color4 object
  1912. */
  1913. Color4.prototype.scale = function (scale) {
  1914. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1915. };
  1916. /**
  1917. * Multiplies the current Color4 values by scale and stores the result in "result"
  1918. * @param scale defines the scaling factor to apply
  1919. * @param result defines the Color4 object where to store the result
  1920. * @returns the current unmodified Color4
  1921. */
  1922. Color4.prototype.scaleToRef = function (scale, result) {
  1923. result.r = this.r * scale;
  1924. result.g = this.g * scale;
  1925. result.b = this.b * scale;
  1926. result.a = this.a * scale;
  1927. return this;
  1928. };
  1929. /**
  1930. * Scale the current Color4 values by a factor and add the result to a given Color4
  1931. * @param scale defines the scale factor
  1932. * @param result defines the Color4 object where to store the result
  1933. * @returns the unmodified current Color4
  1934. */
  1935. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1936. result.r += this.r * scale;
  1937. result.g += this.g * scale;
  1938. result.b += this.b * scale;
  1939. result.a += this.a * scale;
  1940. return this;
  1941. };
  1942. /**
  1943. * Clamps the rgb values by the min and max values and stores the result into "result"
  1944. * @param min defines minimum clamping value (default is 0)
  1945. * @param max defines maximum clamping value (default is 1)
  1946. * @param result defines color to store the result into.
  1947. * @returns the cuurent Color4
  1948. */
  1949. Color4.prototype.clampToRef = function (min, max, result) {
  1950. if (min === void 0) { min = 0; }
  1951. if (max === void 0) { max = 1; }
  1952. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1953. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1954. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1955. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1956. return this;
  1957. };
  1958. /**
  1959. * Multipy an Color4 value by another and return a new Color4 object
  1960. * @param color defines the Color4 value to multiply by
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.multiply = function (color) {
  1964. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1965. };
  1966. /**
  1967. * Multipy a Color4 value by another and push the result in a reference value
  1968. * @param color defines the Color4 value to multiply by
  1969. * @param result defines the Color4 to fill the result in
  1970. * @returns the result Color4
  1971. */
  1972. Color4.prototype.multiplyToRef = function (color, result) {
  1973. result.r = this.r * color.r;
  1974. result.g = this.g * color.g;
  1975. result.b = this.b * color.b;
  1976. result.a = this.a * color.a;
  1977. return result;
  1978. };
  1979. /**
  1980. * Creates a string with the Color4 current values
  1981. * @returns the string representation of the Color4 object
  1982. */
  1983. Color4.prototype.toString = function () {
  1984. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1985. };
  1986. /**
  1987. * Returns the string "Color4"
  1988. * @returns "Color4"
  1989. */
  1990. Color4.prototype.getClassName = function () {
  1991. return "Color4";
  1992. };
  1993. /**
  1994. * Compute the Color4 hash code
  1995. * @returns an unique number that can be used to hash Color4 objects
  1996. */
  1997. Color4.prototype.getHashCode = function () {
  1998. var hash = this.r || 0;
  1999. hash = (hash * 397) ^ (this.g || 0);
  2000. hash = (hash * 397) ^ (this.b || 0);
  2001. hash = (hash * 397) ^ (this.a || 0);
  2002. return hash;
  2003. };
  2004. /**
  2005. * Creates a new Color4 copied from the current one
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.clone = function () {
  2009. return new Color4(this.r, this.g, this.b, this.a);
  2010. };
  2011. /**
  2012. * Copies the given Color4 values into the current one
  2013. * @param source defines the source Color4 object
  2014. * @returns the current updated Color4 object
  2015. */
  2016. Color4.prototype.copyFrom = function (source) {
  2017. this.r = source.r;
  2018. this.g = source.g;
  2019. this.b = source.b;
  2020. this.a = source.a;
  2021. return this;
  2022. };
  2023. /**
  2024. * Copies the given float values into the current one
  2025. * @param r defines the red component to read from
  2026. * @param g defines the green component to read from
  2027. * @param b defines the blue component to read from
  2028. * @param a defines the alpha component to read from
  2029. * @returns the current updated Color4 object
  2030. */
  2031. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2032. this.r = r;
  2033. this.g = g;
  2034. this.b = b;
  2035. this.a = a;
  2036. return this;
  2037. };
  2038. /**
  2039. * Copies the given float values into the current one
  2040. * @param r defines the red component to read from
  2041. * @param g defines the green component to read from
  2042. * @param b defines the blue component to read from
  2043. * @param a defines the alpha component to read from
  2044. * @returns the current updated Color4 object
  2045. */
  2046. Color4.prototype.set = function (r, g, b, a) {
  2047. return this.copyFromFloats(r, g, b, a);
  2048. };
  2049. /**
  2050. * Compute the Color4 hexadecimal code as a string
  2051. * @returns a string containing the hexadecimal representation of the Color4 object
  2052. */
  2053. Color4.prototype.toHexString = function () {
  2054. var intR = (this.r * 255) | 0;
  2055. var intG = (this.g * 255) | 0;
  2056. var intB = (this.b * 255) | 0;
  2057. var intA = (this.a * 255) | 0;
  2058. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to linear space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toLinearSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toLinearSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the linear space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. /**
  2082. * Computes a new Color4 converted from the current one to gamma space
  2083. * @returns a new Color4 object
  2084. */
  2085. Color4.prototype.toGammaSpace = function () {
  2086. var convertedColor = new Color4();
  2087. this.toGammaSpaceToRef(convertedColor);
  2088. return convertedColor;
  2089. };
  2090. /**
  2091. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2092. * @param convertedColor defines the Color4 object where to store the gamma space version
  2093. * @returns the unmodified Color4
  2094. */
  2095. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2096. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2097. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2098. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2099. convertedColor.a = this.a;
  2100. return this;
  2101. };
  2102. // Statics
  2103. /**
  2104. * Creates a new Color4 from the string containing valid hexadecimal values
  2105. * @param hex defines a string containing valid hexadecimal values
  2106. * @returns a new Color4 object
  2107. */
  2108. Color4.FromHexString = function (hex) {
  2109. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2110. return new Color4(0.0, 0.0, 0.0, 0.0);
  2111. }
  2112. var r = parseInt(hex.substring(1, 3), 16);
  2113. var g = parseInt(hex.substring(3, 5), 16);
  2114. var b = parseInt(hex.substring(5, 7), 16);
  2115. var a = parseInt(hex.substring(7, 9), 16);
  2116. return Color4.FromInts(r, g, b, a);
  2117. };
  2118. /**
  2119. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2120. * @param left defines the start value
  2121. * @param right defines the end value
  2122. * @param amount defines the gradient factor
  2123. * @returns a new Color4 object
  2124. */
  2125. Color4.Lerp = function (left, right, amount) {
  2126. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2127. Color4.LerpToRef(left, right, amount, result);
  2128. return result;
  2129. };
  2130. /**
  2131. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2132. * @param left defines the start value
  2133. * @param right defines the end value
  2134. * @param amount defines the gradient factor
  2135. * @param result defines the Color4 object where to store data
  2136. */
  2137. Color4.LerpToRef = function (left, right, amount, result) {
  2138. result.r = left.r + (right.r - left.r) * amount;
  2139. result.g = left.g + (right.g - left.g) * amount;
  2140. result.b = left.b + (right.b - left.b) * amount;
  2141. result.a = left.a + (right.a - left.a) * amount;
  2142. };
  2143. /**
  2144. * Creates a new Color4 from the starting index element of the given array
  2145. * @param array defines the source array to read from
  2146. * @param offset defines the offset in the source array
  2147. * @returns a new Color4 object
  2148. */
  2149. Color4.FromArray = function (array, offset) {
  2150. if (offset === void 0) { offset = 0; }
  2151. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2152. };
  2153. /**
  2154. * Creates a new Color3 from integer values (< 256)
  2155. * @param r defines the red component to read from (value between 0 and 255)
  2156. * @param g defines the green component to read from (value between 0 and 255)
  2157. * @param b defines the blue component to read from (value between 0 and 255)
  2158. * @param a defines the alpha component to read from (value between 0 and 255)
  2159. * @returns a new Color3 object
  2160. */
  2161. Color4.FromInts = function (r, g, b, a) {
  2162. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2163. };
  2164. /**
  2165. * Check the content of a given array and convert it to an array containing RGBA data
  2166. * If the original array was already containing count * 4 values then it is returned directly
  2167. * @param colors defines the array to check
  2168. * @param count defines the number of RGBA data to expect
  2169. * @returns an array containing count * 4 values (RGBA)
  2170. */
  2171. Color4.CheckColors4 = function (colors, count) {
  2172. // Check if color3 was used
  2173. if (colors.length === count * 3) {
  2174. var colors4 = [];
  2175. for (var index = 0; index < colors.length; index += 3) {
  2176. var newIndex = (index / 3) * 4;
  2177. colors4[newIndex] = colors[index];
  2178. colors4[newIndex + 1] = colors[index + 1];
  2179. colors4[newIndex + 2] = colors[index + 2];
  2180. colors4[newIndex + 3] = 1.0;
  2181. }
  2182. return colors4;
  2183. }
  2184. return colors;
  2185. };
  2186. return Color4;
  2187. }());
  2188. BABYLON.Color4 = Color4;
  2189. /**
  2190. * Class representing a vector containing 2 coordinates
  2191. */
  2192. var Vector2 = /** @class */ (function () {
  2193. /**
  2194. * Creates a new Vector2 from the given x and y coordinates
  2195. * @param x defines the first coordinate
  2196. * @param y defines the second coordinate
  2197. */
  2198. function Vector2(
  2199. /** defines the first coordinate */
  2200. x,
  2201. /** defines the second coordinate */
  2202. y) {
  2203. if (x === void 0) { x = 0; }
  2204. if (y === void 0) { y = 0; }
  2205. this.x = x;
  2206. this.y = y;
  2207. }
  2208. /**
  2209. * Gets a string with the Vector2 coordinates
  2210. * @returns a string with the Vector2 coordinates
  2211. */
  2212. Vector2.prototype.toString = function () {
  2213. return "{X: " + this.x + " Y:" + this.y + "}";
  2214. };
  2215. /**
  2216. * Gets class name
  2217. * @returns the string "Vector2"
  2218. */
  2219. Vector2.prototype.getClassName = function () {
  2220. return "Vector2";
  2221. };
  2222. /**
  2223. * Gets current vector hash code
  2224. * @returns the Vector2 hash code as a number
  2225. */
  2226. Vector2.prototype.getHashCode = function () {
  2227. var hash = this.x || 0;
  2228. hash = (hash * 397) ^ (this.y || 0);
  2229. return hash;
  2230. };
  2231. // Operators
  2232. /**
  2233. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2234. * @param array defines the source array
  2235. * @param index defines the offset in source array
  2236. * @returns the current Vector2
  2237. */
  2238. Vector2.prototype.toArray = function (array, index) {
  2239. if (index === void 0) { index = 0; }
  2240. array[index] = this.x;
  2241. array[index + 1] = this.y;
  2242. return this;
  2243. };
  2244. /**
  2245. * Copy the current vector to an array
  2246. * @returns a new array with 2 elements: the Vector2 coordinates.
  2247. */
  2248. Vector2.prototype.asArray = function () {
  2249. var result = new Array();
  2250. this.toArray(result, 0);
  2251. return result;
  2252. };
  2253. /**
  2254. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2255. * @param source defines the source Vector2
  2256. * @returns the current updated Vector2
  2257. */
  2258. Vector2.prototype.copyFrom = function (source) {
  2259. this.x = source.x;
  2260. this.y = source.y;
  2261. return this;
  2262. };
  2263. /**
  2264. * Sets the Vector2 coordinates with the given floats
  2265. * @param x defines the first coordinate
  2266. * @param y defines the second coordinate
  2267. * @returns the current updated Vector2
  2268. */
  2269. Vector2.prototype.copyFromFloats = function (x, y) {
  2270. this.x = x;
  2271. this.y = y;
  2272. return this;
  2273. };
  2274. /**
  2275. * Sets the Vector2 coordinates with the given floats
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. * @returns the current updated Vector2
  2279. */
  2280. Vector2.prototype.set = function (x, y) {
  2281. return this.copyFromFloats(x, y);
  2282. };
  2283. /**
  2284. * Add another vector with the current one
  2285. * @param otherVector defines the other vector
  2286. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2287. */
  2288. Vector2.prototype.add = function (otherVector) {
  2289. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2290. };
  2291. /**
  2292. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2293. * @param otherVector defines the other vector
  2294. * @param result defines the target vector
  2295. * @returns the unmodified current Vector2
  2296. */
  2297. Vector2.prototype.addToRef = function (otherVector, result) {
  2298. result.x = this.x + otherVector.x;
  2299. result.y = this.y + otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2304. * @param otherVector defines the other vector
  2305. * @returns the current updated Vector2
  2306. */
  2307. Vector2.prototype.addInPlace = function (otherVector) {
  2308. this.x += otherVector.x;
  2309. this.y += otherVector.y;
  2310. return this;
  2311. };
  2312. /**
  2313. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2314. * @param otherVector defines the other vector
  2315. * @returns a new Vector2
  2316. */
  2317. Vector2.prototype.addVector3 = function (otherVector) {
  2318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2319. };
  2320. /**
  2321. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2322. * @param otherVector defines the other vector
  2323. * @returns a new Vector2
  2324. */
  2325. Vector2.prototype.subtract = function (otherVector) {
  2326. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2327. };
  2328. /**
  2329. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2330. * @param otherVector defines the other vector
  2331. * @param result defines the target vector
  2332. * @returns the unmodified current Vector2
  2333. */
  2334. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2335. result.x = this.x - otherVector.x;
  2336. result.y = this.y - otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns the current updated Vector2
  2343. */
  2344. Vector2.prototype.subtractInPlace = function (otherVector) {
  2345. this.x -= otherVector.x;
  2346. this.y -= otherVector.y;
  2347. return this;
  2348. };
  2349. /**
  2350. * Multiplies in place the current Vector2 coordinates by the given ones
  2351. * @param otherVector defines the other vector
  2352. * @returns the current updated Vector2
  2353. */
  2354. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2355. this.x *= otherVector.x;
  2356. this.y *= otherVector.y;
  2357. return this;
  2358. };
  2359. /**
  2360. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.multiply = function (otherVector) {
  2365. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2366. };
  2367. /**
  2368. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2374. result.x = this.x * otherVector.x;
  2375. result.y = this.y * otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2380. * @param x defines the first coordinate
  2381. * @param y defines the second coordinate
  2382. * @returns a new Vector2
  2383. */
  2384. Vector2.prototype.multiplyByFloats = function (x, y) {
  2385. return new Vector2(this.x * x, this.y * y);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2389. * @param otherVector defines the other vector
  2390. * @returns a new Vector2
  2391. */
  2392. Vector2.prototype.divide = function (otherVector) {
  2393. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2394. };
  2395. /**
  2396. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2397. * @param otherVector defines the other vector
  2398. * @param result defines the target vector
  2399. * @returns the unmodified current Vector2
  2400. */
  2401. Vector2.prototype.divideToRef = function (otherVector, result) {
  2402. result.x = this.x / otherVector.x;
  2403. result.y = this.y / otherVector.y;
  2404. return this;
  2405. };
  2406. /**
  2407. * Divides the current Vector3 coordinates by the given ones
  2408. * @param otherVector defines the other vector
  2409. * @returns the current updated Vector2
  2410. */
  2411. Vector2.prototype.divideInPlace = function (otherVector) {
  2412. return this.divideToRef(otherVector, this);
  2413. };
  2414. /**
  2415. * Gets a new Vector2 with current Vector2 negated coordinates
  2416. * @returns a new Vector2
  2417. */
  2418. Vector2.prototype.negate = function () {
  2419. return new Vector2(-this.x, -this.y);
  2420. };
  2421. /**
  2422. * Multiply the Vector2 coordinates by scale
  2423. * @param scale defines the scaling factor
  2424. * @returns the current updated Vector2
  2425. */
  2426. Vector2.prototype.scaleInPlace = function (scale) {
  2427. this.x *= scale;
  2428. this.y *= scale;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2433. * @param scale defines the scaling factor
  2434. * @returns a new Vector2
  2435. */
  2436. Vector2.prototype.scale = function (scale) {
  2437. var result = new Vector2(0, 0);
  2438. this.scaleToRef(scale, result);
  2439. return result;
  2440. };
  2441. /**
  2442. * Scale the current Vector2 values by a factor to a given Vector2
  2443. * @param scale defines the scale factor
  2444. * @param result defines the Vector2 object where to store the result
  2445. * @returns the unmodified current Vector2
  2446. */
  2447. Vector2.prototype.scaleToRef = function (scale, result) {
  2448. result.x = this.x * scale;
  2449. result.y = this.y * scale;
  2450. return this;
  2451. };
  2452. /**
  2453. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2454. * @param scale defines the scale factor
  2455. * @param result defines the Vector2 object where to store the result
  2456. * @returns the unmodified current Vector2
  2457. */
  2458. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2459. result.x += this.x * scale;
  2460. result.y += this.y * scale;
  2461. return this;
  2462. };
  2463. /**
  2464. * Gets a boolean if two vectors are equals
  2465. * @param otherVector defines the other vector
  2466. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2467. */
  2468. Vector2.prototype.equals = function (otherVector) {
  2469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2470. };
  2471. /**
  2472. * Gets a boolean if two vectors are equals (using an epsilon value)
  2473. * @param otherVector defines the other vector
  2474. * @param epsilon defines the minimal distance to consider equality
  2475. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2476. */
  2477. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2478. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2479. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2480. };
  2481. // Properties
  2482. /**
  2483. * Gets the length of the vector
  2484. * @returns the vector length (float)
  2485. */
  2486. Vector2.prototype.length = function () {
  2487. return Math.sqrt(this.x * this.x + this.y * this.y);
  2488. };
  2489. /**
  2490. * Gets the vector squared length
  2491. * @returns the vector squared length (float)
  2492. */
  2493. Vector2.prototype.lengthSquared = function () {
  2494. return (this.x * this.x + this.y * this.y);
  2495. };
  2496. // Methods
  2497. /**
  2498. * Normalize the vector
  2499. * @returns the current updated Vector2
  2500. */
  2501. Vector2.prototype.normalize = function () {
  2502. var len = this.length();
  2503. if (len === 0)
  2504. return this;
  2505. var num = 1.0 / len;
  2506. this.x *= num;
  2507. this.y *= num;
  2508. return this;
  2509. };
  2510. /**
  2511. * Gets a new Vector2 copied from the Vector2
  2512. * @returns a new Vector2
  2513. */
  2514. Vector2.prototype.clone = function () {
  2515. return new Vector2(this.x, this.y);
  2516. };
  2517. // Statics
  2518. /**
  2519. * Gets a new Vector2(0, 0)
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.Zero = function () {
  2523. return new Vector2(0, 0);
  2524. };
  2525. /**
  2526. * Gets a new Vector2(1, 1)
  2527. * @returns a new Vector2
  2528. */
  2529. Vector2.One = function () {
  2530. return new Vector2(1, 1);
  2531. };
  2532. /**
  2533. * Gets a new Vector2 set from the given index element of the given array
  2534. * @param array defines the data source
  2535. * @param offset defines the offset in the data source
  2536. * @returns a new Vector2
  2537. */
  2538. Vector2.FromArray = function (array, offset) {
  2539. if (offset === void 0) { offset = 0; }
  2540. return new Vector2(array[offset], array[offset + 1]);
  2541. };
  2542. /**
  2543. * Sets "result" from the given index element of the given array
  2544. * @param array defines the data source
  2545. * @param offset defines the offset in the data source
  2546. * @param result defines the target vector
  2547. */
  2548. Vector2.FromArrayToRef = function (array, offset, result) {
  2549. result.x = array[offset];
  2550. result.y = array[offset + 1];
  2551. };
  2552. /**
  2553. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2554. * @param value1 defines 1st point of control
  2555. * @param value2 defines 2nd point of control
  2556. * @param value3 defines 3rd point of control
  2557. * @param value4 defines 4th point of control
  2558. * @param amount defines the interpolation factor
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2562. var squared = amount * amount;
  2563. var cubed = amount * squared;
  2564. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2565. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2566. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2567. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2568. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2569. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2570. return new Vector2(x, y);
  2571. };
  2572. /**
  2573. * 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".
  2574. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2575. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2576. * @param value defines the value to clamp
  2577. * @param min defines the lower limit
  2578. * @param max defines the upper limit
  2579. * @returns a new Vector2
  2580. */
  2581. Vector2.Clamp = function (value, min, max) {
  2582. var x = value.x;
  2583. x = (x > max.x) ? max.x : x;
  2584. x = (x < min.x) ? min.x : x;
  2585. var y = value.y;
  2586. y = (y > max.y) ? max.y : y;
  2587. y = (y < min.y) ? min.y : y;
  2588. return new Vector2(x, y);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2592. * @param value1 defines the 1st control point
  2593. * @param tangent1 defines the outgoing tangent
  2594. * @param value2 defines the 2nd control point
  2595. * @param tangent2 defines the incoming tangent
  2596. * @param amount defines the interpolation factor
  2597. * @returns a new Vector2
  2598. */
  2599. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2600. var squared = amount * amount;
  2601. var cubed = amount * squared;
  2602. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2603. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2604. var part3 = (cubed - (2.0 * squared)) + amount;
  2605. var part4 = cubed - squared;
  2606. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2607. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2608. return new Vector2(x, y);
  2609. };
  2610. /**
  2611. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2612. * @param start defines the start vector
  2613. * @param end defines the end vector
  2614. * @param amount defines the interpolation factor
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Lerp = function (start, end, amount) {
  2618. var x = start.x + ((end.x - start.x) * amount);
  2619. var y = start.y + ((end.y - start.y) * amount);
  2620. return new Vector2(x, y);
  2621. };
  2622. /**
  2623. * Gets the dot product of the vector "left" and the vector "right"
  2624. * @param left defines first vector
  2625. * @param right defines second vector
  2626. * @returns the dot product (float)
  2627. */
  2628. Vector2.Dot = function (left, right) {
  2629. return left.x * right.x + left.y * right.y;
  2630. };
  2631. /**
  2632. * Returns a new Vector2 equal to the normalized given vector
  2633. * @param vector defines the vector to normalize
  2634. * @returns a new Vector2
  2635. */
  2636. Vector2.Normalize = function (vector) {
  2637. var newVector = vector.clone();
  2638. newVector.normalize();
  2639. return newVector;
  2640. };
  2641. /**
  2642. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2643. * @param left defines 1st vector
  2644. * @param right defines 2nd vector
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.Minimize = function (left, right) {
  2648. var x = (left.x < right.x) ? left.x : right.x;
  2649. var y = (left.y < right.y) ? left.y : right.y;
  2650. return new Vector2(x, y);
  2651. };
  2652. /**
  2653. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2654. * @param left defines 1st vector
  2655. * @param right defines 2nd vector
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Maximize = function (left, right) {
  2659. var x = (left.x > right.x) ? left.x : right.x;
  2660. var y = (left.y > right.y) ? left.y : right.y;
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2665. * @param vector defines the vector to transform
  2666. * @param transformation defines the matrix to apply
  2667. * @returns a new Vector2
  2668. */
  2669. Vector2.Transform = function (vector, transformation) {
  2670. var r = Vector2.Zero();
  2671. Vector2.TransformToRef(vector, transformation, r);
  2672. return r;
  2673. };
  2674. /**
  2675. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2676. * @param vector defines the vector to transform
  2677. * @param transformation defines the matrix to apply
  2678. * @param result defines the target vector
  2679. */
  2680. Vector2.TransformToRef = function (vector, transformation, result) {
  2681. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2682. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2683. result.x = x;
  2684. result.y = y;
  2685. };
  2686. /**
  2687. * Determines if a given vector is included in a triangle
  2688. * @param p defines the vector to test
  2689. * @param p0 defines 1st triangle point
  2690. * @param p1 defines 2nd triangle point
  2691. * @param p2 defines 3rd triangle point
  2692. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2693. */
  2694. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2695. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2696. var sign = a < 0 ? -1 : 1;
  2697. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2698. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2699. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2700. };
  2701. /**
  2702. * Gets the distance between the vectors "value1" and "value2"
  2703. * @param value1 defines first vector
  2704. * @param value2 defines second vector
  2705. * @returns the distance between vectors
  2706. */
  2707. Vector2.Distance = function (value1, value2) {
  2708. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2709. };
  2710. /**
  2711. * Returns the squared distance between the vectors "value1" and "value2"
  2712. * @param value1 defines first vector
  2713. * @param value2 defines second vector
  2714. * @returns the squared distance between vectors
  2715. */
  2716. Vector2.DistanceSquared = function (value1, value2) {
  2717. var x = value1.x - value2.x;
  2718. var y = value1.y - value2.y;
  2719. return (x * x) + (y * y);
  2720. };
  2721. /**
  2722. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2723. * @param value1 defines first vector
  2724. * @param value2 defines second vector
  2725. * @returns a new Vector2
  2726. */
  2727. Vector2.Center = function (value1, value2) {
  2728. var center = value1.add(value2);
  2729. center.scaleInPlace(0.5);
  2730. return center;
  2731. };
  2732. /**
  2733. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2734. * @param p defines the middle point
  2735. * @param segA defines one point of the segment
  2736. * @param segB defines the other point of the segment
  2737. * @returns the shortest distance
  2738. */
  2739. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2740. var l2 = Vector2.DistanceSquared(segA, segB);
  2741. if (l2 === 0.0) {
  2742. return Vector2.Distance(p, segA);
  2743. }
  2744. var v = segB.subtract(segA);
  2745. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2746. var proj = segA.add(v.multiplyByFloats(t, t));
  2747. return Vector2.Distance(p, proj);
  2748. };
  2749. return Vector2;
  2750. }());
  2751. BABYLON.Vector2 = Vector2;
  2752. /**
  2753. * Classed used to store (x,y,z) vector representation
  2754. * A Vector3 is the main object used in 3D geometry
  2755. * It can represent etiher the coordinates of a point the space, either a direction
  2756. * Reminder: Babylon.js uses a left handed forward facing system
  2757. */
  2758. var Vector3 = /** @class */ (function () {
  2759. /**
  2760. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2761. * @param x defines the first coordinates (on X axis)
  2762. * @param y defines the second coordinates (on Y axis)
  2763. * @param z defines the third coordinates (on Z axis)
  2764. */
  2765. function Vector3(
  2766. /**
  2767. * Defines the first coordinates (on X axis)
  2768. */
  2769. x,
  2770. /**
  2771. * Defines the second coordinates (on Y axis)
  2772. */
  2773. y,
  2774. /**
  2775. * Defines the third coordinates (on Z axis)
  2776. */
  2777. z) {
  2778. if (x === void 0) { x = 0; }
  2779. if (y === void 0) { y = 0; }
  2780. if (z === void 0) { z = 0; }
  2781. this.x = x;
  2782. this.y = y;
  2783. this.z = z;
  2784. }
  2785. /**
  2786. * Creates a string representation of the Vector3
  2787. * @returns a string with the Vector3 coordinates.
  2788. */
  2789. Vector3.prototype.toString = function () {
  2790. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2791. };
  2792. /**
  2793. * Gets the class name
  2794. * @returns the string "Vector3"
  2795. */
  2796. Vector3.prototype.getClassName = function () {
  2797. return "Vector3";
  2798. };
  2799. /**
  2800. * Creates the Vector3 hash code
  2801. * @returns a number which tends to be unique between Vector3 instances
  2802. */
  2803. Vector3.prototype.getHashCode = function () {
  2804. var hash = this.x || 0;
  2805. hash = (hash * 397) ^ (this.y || 0);
  2806. hash = (hash * 397) ^ (this.z || 0);
  2807. return hash;
  2808. };
  2809. // Operators
  2810. /**
  2811. * Creates an array containing three elements : the coordinates of the Vector3
  2812. * @returns a new array of numbers
  2813. */
  2814. Vector3.prototype.asArray = function () {
  2815. var result = [];
  2816. this.toArray(result, 0);
  2817. return result;
  2818. };
  2819. /**
  2820. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2821. * @param array defines the destination array
  2822. * @param index defines the offset in the destination array
  2823. * @returns the current Vector3
  2824. */
  2825. Vector3.prototype.toArray = function (array, index) {
  2826. if (index === void 0) { index = 0; }
  2827. array[index] = this.x;
  2828. array[index + 1] = this.y;
  2829. array[index + 2] = this.z;
  2830. return this;
  2831. };
  2832. /**
  2833. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2834. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2835. */
  2836. Vector3.prototype.toQuaternion = function () {
  2837. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2838. };
  2839. /**
  2840. * Adds the given vector to the current Vector3
  2841. * @param otherVector defines the second operand
  2842. * @returns the current updated Vector3
  2843. */
  2844. Vector3.prototype.addInPlace = function (otherVector) {
  2845. this.x += otherVector.x;
  2846. this.y += otherVector.y;
  2847. this.z += otherVector.z;
  2848. return this;
  2849. };
  2850. /**
  2851. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2852. * @param otherVector defines the second operand
  2853. * @returns the resulting Vector3
  2854. */
  2855. Vector3.prototype.add = function (otherVector) {
  2856. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2857. };
  2858. /**
  2859. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2860. * @param otherVector defines the second operand
  2861. * @param result defines the Vector3 object where to store the result
  2862. * @returns the current Vector3
  2863. */
  2864. Vector3.prototype.addToRef = function (otherVector, result) {
  2865. result.x = this.x + otherVector.x;
  2866. result.y = this.y + otherVector.y;
  2867. result.z = this.z + otherVector.z;
  2868. return this;
  2869. };
  2870. /**
  2871. * Subtract the given vector from the current Vector3
  2872. * @param otherVector defines the second operand
  2873. * @returns the current updated Vector3
  2874. */
  2875. Vector3.prototype.subtractInPlace = function (otherVector) {
  2876. this.x -= otherVector.x;
  2877. this.y -= otherVector.y;
  2878. this.z -= otherVector.z;
  2879. return this;
  2880. };
  2881. /**
  2882. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2883. * @param otherVector defines the second operand
  2884. * @returns the resulting Vector3
  2885. */
  2886. Vector3.prototype.subtract = function (otherVector) {
  2887. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2888. };
  2889. /**
  2890. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2891. * @param otherVector defines the second operand
  2892. * @param result defines the Vector3 object where to store the result
  2893. * @returns the current Vector3
  2894. */
  2895. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2896. result.x = this.x - otherVector.x;
  2897. result.y = this.y - otherVector.y;
  2898. result.z = this.z - otherVector.z;
  2899. return this;
  2900. };
  2901. /**
  2902. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2903. * @param x defines the x coordinate of the operand
  2904. * @param y defines the y coordinate of the operand
  2905. * @param z defines the z coordinate of the operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2909. return new Vector3(this.x - x, this.y - y, this.z - z);
  2910. };
  2911. /**
  2912. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2913. * @param x defines the x coordinate of the operand
  2914. * @param y defines the y coordinate of the operand
  2915. * @param z defines the z coordinate of the operand
  2916. * @param result defines the Vector3 object where to store the result
  2917. * @returns the current Vector3
  2918. */
  2919. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2920. result.x = this.x - x;
  2921. result.y = this.y - y;
  2922. result.z = this.z - z;
  2923. return this;
  2924. };
  2925. /**
  2926. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2927. * @returns a new Vector3
  2928. */
  2929. Vector3.prototype.negate = function () {
  2930. return new Vector3(-this.x, -this.y, -this.z);
  2931. };
  2932. /**
  2933. * Multiplies the Vector3 coordinates by the float "scale"
  2934. * @param scale defines the multiplier factor
  2935. * @returns the current updated Vector3
  2936. */
  2937. Vector3.prototype.scaleInPlace = function (scale) {
  2938. this.x *= scale;
  2939. this.y *= scale;
  2940. this.z *= scale;
  2941. return this;
  2942. };
  2943. /**
  2944. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2945. * @param scale defines the multiplier factor
  2946. * @returns a new Vector3
  2947. */
  2948. Vector3.prototype.scale = function (scale) {
  2949. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2950. };
  2951. /**
  2952. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2953. * @param scale defines the multiplier factor
  2954. * @param result defines the Vector3 object where to store the result
  2955. * @returns the current Vector3
  2956. */
  2957. Vector3.prototype.scaleToRef = function (scale, result) {
  2958. result.x = this.x * scale;
  2959. result.y = this.y * scale;
  2960. result.z = this.z * scale;
  2961. return this;
  2962. };
  2963. /**
  2964. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2965. * @param scale defines the scale factor
  2966. * @param result defines the Vector3 object where to store the result
  2967. * @returns the unmodified current Vector3
  2968. */
  2969. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2970. result.x += this.x * scale;
  2971. result.y += this.y * scale;
  2972. result.z += this.z * scale;
  2973. return this;
  2974. };
  2975. /**
  2976. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2977. * @param otherVector defines the second operand
  2978. * @returns true if both vectors are equals
  2979. */
  2980. Vector3.prototype.equals = function (otherVector) {
  2981. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2982. };
  2983. /**
  2984. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2985. * @param otherVector defines the second operand
  2986. * @param epsilon defines the minimal distance to define values as equals
  2987. * @returns true if both vectors are distant less than epsilon
  2988. */
  2989. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2990. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2991. 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);
  2992. };
  2993. /**
  2994. * Returns true if the current Vector3 coordinates equals the given floats
  2995. * @param x defines the x coordinate of the operand
  2996. * @param y defines the y coordinate of the operand
  2997. * @param z defines the z coordinate of the operand
  2998. * @returns true if both vectors are equals
  2999. */
  3000. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3001. return this.x === x && this.y === y && this.z === z;
  3002. };
  3003. /**
  3004. * Multiplies the current Vector3 coordinates by the given ones
  3005. * @param otherVector defines the second operand
  3006. * @returns the current updated Vector3
  3007. */
  3008. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3009. this.x *= otherVector.x;
  3010. this.y *= otherVector.y;
  3011. this.z *= otherVector.z;
  3012. return this;
  3013. };
  3014. /**
  3015. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3016. * @param otherVector defines the second operand
  3017. * @returns the new Vector3
  3018. */
  3019. Vector3.prototype.multiply = function (otherVector) {
  3020. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3021. };
  3022. /**
  3023. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3024. * @param otherVector defines the second operand
  3025. * @param result defines the Vector3 object where to store the result
  3026. * @returns the current Vector3
  3027. */
  3028. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3029. result.x = this.x * otherVector.x;
  3030. result.y = this.y * otherVector.y;
  3031. result.z = this.z * otherVector.z;
  3032. return this;
  3033. };
  3034. /**
  3035. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3036. * @param x defines the x coordinate of the operand
  3037. * @param y defines the y coordinate of the operand
  3038. * @param z defines the z coordinate of the operand
  3039. * @returns the new Vector3
  3040. */
  3041. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3042. return new Vector3(this.x * x, this.y * y, this.z * z);
  3043. };
  3044. /**
  3045. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3046. * @param otherVector defines the second operand
  3047. * @returns the new Vector3
  3048. */
  3049. Vector3.prototype.divide = function (otherVector) {
  3050. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3051. };
  3052. /**
  3053. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3054. * @param otherVector defines the second operand
  3055. * @param result defines the Vector3 object where to store the result
  3056. * @returns the current Vector3
  3057. */
  3058. Vector3.prototype.divideToRef = function (otherVector, result) {
  3059. result.x = this.x / otherVector.x;
  3060. result.y = this.y / otherVector.y;
  3061. result.z = this.z / otherVector.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Divides the current Vector3 coordinates by the given ones.
  3066. * @param otherVector defines the second operand
  3067. * @returns the current updated Vector3
  3068. */
  3069. Vector3.prototype.divideInPlace = function (otherVector) {
  3070. return this.divideToRef(otherVector, this);
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.minimizeInPlace = function (other) {
  3078. if (other.x < this.x)
  3079. this.x = other.x;
  3080. if (other.y < this.y)
  3081. this.y = other.y;
  3082. if (other.z < this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. /**
  3087. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3088. * @param other defines the second operand
  3089. * @returns the current updated Vector3
  3090. */
  3091. Vector3.prototype.maximizeInPlace = function (other) {
  3092. if (other.x > this.x)
  3093. this.x = other.x;
  3094. if (other.y > this.y)
  3095. this.y = other.y;
  3096. if (other.z > this.z)
  3097. this.z = other.z;
  3098. return this;
  3099. };
  3100. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3101. /**
  3102. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3103. */
  3104. get: function () {
  3105. var absX = Math.abs(this.x);
  3106. var absY = Math.abs(this.y);
  3107. if (absX !== absY) {
  3108. return true;
  3109. }
  3110. var absZ = Math.abs(this.z);
  3111. if (absX !== absZ) {
  3112. return true;
  3113. }
  3114. if (absY !== absZ) {
  3115. return true;
  3116. }
  3117. return false;
  3118. },
  3119. enumerable: true,
  3120. configurable: true
  3121. });
  3122. // Properties
  3123. /**
  3124. * Gets the length of the Vector3
  3125. * @returns the length of the Vecto3
  3126. */
  3127. Vector3.prototype.length = function () {
  3128. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3129. };
  3130. /**
  3131. * Gets the squared length of the Vector3
  3132. * @returns squared length of the Vector3
  3133. */
  3134. Vector3.prototype.lengthSquared = function () {
  3135. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3136. };
  3137. /**
  3138. * Normalize the current Vector3.
  3139. * Please note that this is an in place operation.
  3140. * @returns the current updated Vector3
  3141. */
  3142. Vector3.prototype.normalize = function () {
  3143. var len = this.length();
  3144. if (len === 0 || len === 1.0)
  3145. return this;
  3146. var num = 1.0 / len;
  3147. this.x *= num;
  3148. this.y *= num;
  3149. this.z *= num;
  3150. return this;
  3151. };
  3152. /**
  3153. * Normalize the current Vector3 to a new vector
  3154. * @returns the new Vector3
  3155. */
  3156. Vector3.prototype.normalizeToNew = function () {
  3157. var normalized = new Vector3(0, 0, 0);
  3158. this.normalizeToRef(normalized);
  3159. return normalized;
  3160. };
  3161. /**
  3162. * Normalize the current Vector3 to the reference
  3163. * @param reference define the Vector3 to update
  3164. * @returns the updated Vector3
  3165. */
  3166. Vector3.prototype.normalizeToRef = function (reference) {
  3167. var len = this.length();
  3168. if (len === 0 || len === 1.0) {
  3169. reference.set(this.x, this.y, this.z);
  3170. return reference;
  3171. }
  3172. var scale = 1.0 / len;
  3173. this.scaleToRef(scale, reference);
  3174. return reference;
  3175. };
  3176. /**
  3177. * Creates a new Vector3 copied from the current Vector3
  3178. * @returns the new Vector3
  3179. */
  3180. Vector3.prototype.clone = function () {
  3181. return new Vector3(this.x, this.y, this.z);
  3182. };
  3183. /**
  3184. * Copies the given vector coordinates to the current Vector3 ones
  3185. * @param source defines the source Vector3
  3186. * @returns the current updated Vector3
  3187. */
  3188. Vector3.prototype.copyFrom = function (source) {
  3189. this.x = source.x;
  3190. this.y = source.y;
  3191. this.z = source.z;
  3192. return this;
  3193. };
  3194. /**
  3195. * Copies the given floats to the current Vector3 coordinates
  3196. * @param x defines the x coordinate of the operand
  3197. * @param y defines the y coordinate of the operand
  3198. * @param z defines the z coordinate of the operand
  3199. * @returns the current updated Vector3
  3200. */
  3201. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3202. this.x = x;
  3203. this.y = y;
  3204. this.z = z;
  3205. return this;
  3206. };
  3207. /**
  3208. * Copies the given floats to the current Vector3 coordinates
  3209. * @param x defines the x coordinate of the operand
  3210. * @param y defines the y coordinate of the operand
  3211. * @param z defines the z coordinate of the operand
  3212. * @returns the current updated Vector3
  3213. */
  3214. Vector3.prototype.set = function (x, y, z) {
  3215. return this.copyFromFloats(x, y, z);
  3216. };
  3217. // Statics
  3218. /**
  3219. * Get the clip factor between two vectors
  3220. * @param vector0 defines the first operand
  3221. * @param vector1 defines the second operand
  3222. * @param axis defines the axis to use
  3223. * @param size defines the size along the axis
  3224. * @returns the clip factor
  3225. */
  3226. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3227. var d0 = Vector3.Dot(vector0, axis) - size;
  3228. var d1 = Vector3.Dot(vector1, axis) - size;
  3229. var s = d0 / (d0 - d1);
  3230. return s;
  3231. };
  3232. /**
  3233. * Get angle between two vectors
  3234. * @param vector0 angle between vector0 and vector1
  3235. * @param vector1 angle between vector0 and vector1
  3236. * @param normal direction of the normal
  3237. * @return the angle between vector0 and vector1
  3238. */
  3239. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3240. var v0 = vector0.clone().normalize();
  3241. var v1 = vector1.clone().normalize();
  3242. var dot = Vector3.Dot(v0, v1);
  3243. var n = Vector3.Cross(v0, v1);
  3244. if (Vector3.Dot(n, normal) > 0) {
  3245. return Math.acos(dot);
  3246. }
  3247. return -Math.acos(dot);
  3248. };
  3249. /**
  3250. * Returns a new Vector3 set from the index "offset" of the given array
  3251. * @param array defines the source array
  3252. * @param offset defines the offset in the source array
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.FromArray = function (array, offset) {
  3256. if (!offset) {
  3257. offset = 0;
  3258. }
  3259. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3260. };
  3261. /**
  3262. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3263. * This function is deprecated. Use FromArray instead
  3264. * @param array defines the source array
  3265. * @param offset defines the offset in the source array
  3266. * @returns the new Vector3
  3267. */
  3268. Vector3.FromFloatArray = function (array, offset) {
  3269. return Vector3.FromArray(array, offset);
  3270. };
  3271. /**
  3272. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3273. * @param array defines the source array
  3274. * @param offset defines the offset in the source array
  3275. * @param result defines the Vector3 where to store the result
  3276. */
  3277. Vector3.FromArrayToRef = function (array, offset, result) {
  3278. result.x = array[offset];
  3279. result.y = array[offset + 1];
  3280. result.z = array[offset + 2];
  3281. };
  3282. /**
  3283. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3284. * This function is deprecated. Use FromArrayToRef instead.
  3285. * @param array defines the source array
  3286. * @param offset defines the offset in the source array
  3287. * @param result defines the Vector3 where to store the result
  3288. */
  3289. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3290. return Vector3.FromArrayToRef(array, offset, result);
  3291. };
  3292. /**
  3293. * Sets the given vector "result" with the given floats.
  3294. * @param x defines the x coordinate of the source
  3295. * @param y defines the y coordinate of the source
  3296. * @param z defines the z coordinate of the source
  3297. * @param result defines the Vector3 where to store the result
  3298. */
  3299. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3300. result.x = x;
  3301. result.y = y;
  3302. result.z = z;
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3306. * @returns a new empty Vector3
  3307. */
  3308. Vector3.Zero = function () {
  3309. return new Vector3(0.0, 0.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3313. * @returns a new unit Vector3
  3314. */
  3315. Vector3.One = function () {
  3316. return new Vector3(1.0, 1.0, 1.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3320. * @returns a new up Vector3
  3321. */
  3322. Vector3.Up = function () {
  3323. return new Vector3(0.0, 1.0, 0.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3327. * @returns a new down Vector3
  3328. */
  3329. Vector3.Down = function () {
  3330. return new Vector3(0.0, -1.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3334. * @returns a new forward Vector3
  3335. */
  3336. Vector3.Forward = function () {
  3337. return new Vector3(0.0, 0.0, 1.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3341. * @returns a new right Vector3
  3342. */
  3343. Vector3.Right = function () {
  3344. return new Vector3(1.0, 0.0, 0.0);
  3345. };
  3346. /**
  3347. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3348. * @returns a new left Vector3
  3349. */
  3350. Vector3.Left = function () {
  3351. return new Vector3(-1.0, 0.0, 0.0);
  3352. };
  3353. /**
  3354. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3355. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3356. * @param vector defines the Vector3 to transform
  3357. * @param transformation defines the transformation matrix
  3358. * @returns the transformed Vector3
  3359. */
  3360. Vector3.TransformCoordinates = function (vector, transformation) {
  3361. var result = Vector3.Zero();
  3362. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3363. return result;
  3364. };
  3365. /**
  3366. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3367. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3368. * @param vector defines the Vector3 to transform
  3369. * @param transformation defines the transformation matrix
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3373. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3374. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3375. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3376. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3377. result.x = x / w;
  3378. result.y = y / w;
  3379. result.z = z / w;
  3380. };
  3381. /**
  3382. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3383. * This method computes tranformed coordinates only, not transformed direction vectors
  3384. * @param x define the x coordinate of the source vector
  3385. * @param y define the y coordinate of the source vector
  3386. * @param z define the z coordinate of the source vector
  3387. * @param transformation defines the transformation matrix
  3388. * @param result defines the Vector3 where to store the result
  3389. */
  3390. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3391. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3392. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3393. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3394. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3395. result.x = rx / rw;
  3396. result.y = ry / rw;
  3397. result.z = rz / rw;
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3401. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3402. * @param vector defines the Vector3 to transform
  3403. * @param transformation defines the transformation matrix
  3404. * @returns the new Vector3
  3405. */
  3406. Vector3.TransformNormal = function (vector, transformation) {
  3407. var result = Vector3.Zero();
  3408. Vector3.TransformNormalToRef(vector, transformation, result);
  3409. return result;
  3410. };
  3411. /**
  3412. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3413. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3414. * @param vector defines the Vector3 to transform
  3415. * @param transformation defines the transformation matrix
  3416. * @param result defines the Vector3 where to store the result
  3417. */
  3418. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3419. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3420. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3421. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3422. result.x = x;
  3423. result.y = y;
  3424. result.z = z;
  3425. };
  3426. /**
  3427. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3428. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3429. * @param x define the x coordinate of the source vector
  3430. * @param y define the y coordinate of the source vector
  3431. * @param z define the z coordinate of the source vector
  3432. * @param transformation defines the transformation matrix
  3433. * @param result defines the Vector3 where to store the result
  3434. */
  3435. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3436. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3437. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3438. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3439. };
  3440. /**
  3441. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3442. * @param value1 defines the first control point
  3443. * @param value2 defines the second control point
  3444. * @param value3 defines the third control point
  3445. * @param value4 defines the fourth control point
  3446. * @param amount defines the amount on the spline to use
  3447. * @returns the new Vector3
  3448. */
  3449. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3450. var squared = amount * amount;
  3451. var cubed = amount * squared;
  3452. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3453. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3454. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3455. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3456. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3457. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3458. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3459. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3460. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3461. return new Vector3(x, y, z);
  3462. };
  3463. /**
  3464. * 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"
  3465. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3466. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3467. * @param value defines the current value
  3468. * @param min defines the lower range value
  3469. * @param max defines the upper range value
  3470. * @returns the new Vector3
  3471. */
  3472. Vector3.Clamp = function (value, min, max) {
  3473. var x = value.x;
  3474. x = (x > max.x) ? max.x : x;
  3475. x = (x < min.x) ? min.x : x;
  3476. var y = value.y;
  3477. y = (y > max.y) ? max.y : y;
  3478. y = (y < min.y) ? min.y : y;
  3479. var z = value.z;
  3480. z = (z > max.z) ? max.z : z;
  3481. z = (z < min.z) ? min.z : z;
  3482. return new Vector3(x, y, z);
  3483. };
  3484. /**
  3485. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3486. * @param value1 defines the first control point
  3487. * @param tangent1 defines the first tangent vector
  3488. * @param value2 defines the second control point
  3489. * @param tangent2 defines the second tangent vector
  3490. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3491. * @returns the new Vector3
  3492. */
  3493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3494. var squared = amount * amount;
  3495. var cubed = amount * squared;
  3496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3498. var part3 = (cubed - (2.0 * squared)) + amount;
  3499. var part4 = cubed - squared;
  3500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3503. return new Vector3(x, y, z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3507. * @param start defines the start value
  3508. * @param end defines the end value
  3509. * @param amount max defines amount between both (between 0 and 1)
  3510. * @returns the new Vector3
  3511. */
  3512. Vector3.Lerp = function (start, end, amount) {
  3513. var result = new Vector3(0, 0, 0);
  3514. Vector3.LerpToRef(start, end, amount, result);
  3515. return result;
  3516. };
  3517. /**
  3518. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3519. * @param start defines the start value
  3520. * @param end defines the end value
  3521. * @param amount max defines amount between both (between 0 and 1)
  3522. * @param result defines the Vector3 where to store the result
  3523. */
  3524. Vector3.LerpToRef = function (start, end, amount, result) {
  3525. result.x = start.x + ((end.x - start.x) * amount);
  3526. result.y = start.y + ((end.y - start.y) * amount);
  3527. result.z = start.z + ((end.z - start.z) * amount);
  3528. };
  3529. /**
  3530. * Returns the dot product (float) between the vectors "left" and "right"
  3531. * @param left defines the left operand
  3532. * @param right defines the right operand
  3533. * @returns the dot product
  3534. */
  3535. Vector3.Dot = function (left, right) {
  3536. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3537. };
  3538. /**
  3539. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3540. * The cross product is then orthogonal to both "left" and "right"
  3541. * @param left defines the left operand
  3542. * @param right defines the right operand
  3543. * @returns the cross product
  3544. */
  3545. Vector3.Cross = function (left, right) {
  3546. var result = Vector3.Zero();
  3547. Vector3.CrossToRef(left, right, result);
  3548. return result;
  3549. };
  3550. /**
  3551. * Sets the given vector "result" with the cross product of "left" and "right"
  3552. * The cross product is then orthogonal to both "left" and "right"
  3553. * @param left defines the left operand
  3554. * @param right defines the right operand
  3555. * @param result defines the Vector3 where to store the result
  3556. */
  3557. Vector3.CrossToRef = function (left, right, result) {
  3558. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3559. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3560. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3561. result.copyFrom(MathTmp.Vector3[0]);
  3562. };
  3563. /**
  3564. * Returns a new Vector3 as the normalization of the given vector
  3565. * @param vector defines the Vector3 to normalize
  3566. * @returns the new Vector3
  3567. */
  3568. Vector3.Normalize = function (vector) {
  3569. var result = Vector3.Zero();
  3570. Vector3.NormalizeToRef(vector, result);
  3571. return result;
  3572. };
  3573. /**
  3574. * Sets the given vector "result" with the normalization of the given first vector
  3575. * @param vector defines the Vector3 to normalize
  3576. * @param result defines the Vector3 where to store the result
  3577. */
  3578. Vector3.NormalizeToRef = function (vector, result) {
  3579. result.copyFrom(vector);
  3580. result.normalize();
  3581. };
  3582. /**
  3583. * Project a Vector3 onto screen space
  3584. * @param vector defines the Vector3 to project
  3585. * @param world defines the world matrix to use
  3586. * @param transform defines the transform (view x projection) matrix to use
  3587. * @param viewport defines the screen viewport to use
  3588. * @returns the new Vector3
  3589. */
  3590. Vector3.Project = function (vector, world, transform, viewport) {
  3591. var cw = viewport.width;
  3592. var ch = viewport.height;
  3593. var cx = viewport.x;
  3594. var cy = viewport.y;
  3595. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3596. 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);
  3597. var matrix = MathTmp.Matrix[0];
  3598. world.multiplyToRef(transform, matrix);
  3599. matrix.multiplyToRef(viewportMatrix, matrix);
  3600. return Vector3.TransformCoordinates(vector, matrix);
  3601. };
  3602. /**
  3603. * Unproject from screen space to object space
  3604. * @param source defines the screen space Vector3 to use
  3605. * @param viewportWidth defines the current width of the viewport
  3606. * @param viewportHeight defines the current height of the viewport
  3607. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3608. * @param transform defines the transform (view x projection) matrix to use
  3609. * @returns the new Vector3
  3610. */
  3611. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3612. var matrix = MathTmp.Matrix[0];
  3613. world.multiplyToRef(transform, matrix);
  3614. matrix.invert();
  3615. source.x = source.x / viewportWidth * 2 - 1;
  3616. source.y = -(source.y / viewportHeight * 2 - 1);
  3617. var vector = Vector3.TransformCoordinates(source, matrix);
  3618. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3619. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3620. vector = vector.scale(1.0 / num);
  3621. }
  3622. return vector;
  3623. };
  3624. /**
  3625. * Unproject from screen space to object space
  3626. * @param source defines the screen space Vector3 to use
  3627. * @param viewportWidth defines the current width of the viewport
  3628. * @param viewportHeight defines the current height of the viewport
  3629. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3630. * @param view defines the view matrix to use
  3631. * @param projection defines the projection matrix to use
  3632. * @returns the new Vector3
  3633. */
  3634. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3635. var result = Vector3.Zero();
  3636. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3637. return result;
  3638. };
  3639. /**
  3640. * Unproject from screen space to object space
  3641. * @param source defines the screen space Vector3 to use
  3642. * @param viewportWidth defines the current width of the viewport
  3643. * @param viewportHeight defines the current height of the viewport
  3644. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3645. * @param view defines the view matrix to use
  3646. * @param projection defines the projection matrix to use
  3647. * @param result defines the Vector3 where to store the result
  3648. */
  3649. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3650. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3651. };
  3652. /**
  3653. * Unproject from screen space to object space
  3654. * @param sourceX defines the screen space x coordinate to use
  3655. * @param sourceY defines the screen space y coordinate to use
  3656. * @param sourceZ defines the screen space z coordinate to use
  3657. * @param viewportWidth defines the current width of the viewport
  3658. * @param viewportHeight defines the current height of the viewport
  3659. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3660. * @param view defines the view matrix to use
  3661. * @param projection defines the projection matrix to use
  3662. * @param result defines the Vector3 where to store the result
  3663. */
  3664. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3665. var matrix = MathTmp.Matrix[0];
  3666. world.multiplyToRef(view, matrix);
  3667. matrix.multiplyToRef(projection, matrix);
  3668. matrix.invert();
  3669. var screenSource = MathTmp.Vector3[0];
  3670. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3671. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3672. screenSource.z = 2 * sourceZ - 1.0;
  3673. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3674. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3675. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3676. result.scaleInPlace(1.0 / num);
  3677. }
  3678. };
  3679. /**
  3680. * Gets the minimal coordinate values between two Vector3
  3681. * @param left defines the first operand
  3682. * @param right defines the second operand
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Minimize = function (left, right) {
  3686. var min = left.clone();
  3687. min.minimizeInPlace(right);
  3688. return min;
  3689. };
  3690. /**
  3691. * Gets the maximal coordinate values between two Vector3
  3692. * @param left defines the first operand
  3693. * @param right defines the second operand
  3694. * @returns the new Vector3
  3695. */
  3696. Vector3.Maximize = function (left, right) {
  3697. var max = left.clone();
  3698. max.maximizeInPlace(right);
  3699. return max;
  3700. };
  3701. /**
  3702. * Returns the distance between the vectors "value1" and "value2"
  3703. * @param value1 defines the first operand
  3704. * @param value2 defines the second operand
  3705. * @returns the distance
  3706. */
  3707. Vector3.Distance = function (value1, value2) {
  3708. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3709. };
  3710. /**
  3711. * Returns the squared distance between the vectors "value1" and "value2"
  3712. * @param value1 defines the first operand
  3713. * @param value2 defines the second operand
  3714. * @returns the squared distance
  3715. */
  3716. Vector3.DistanceSquared = function (value1, value2) {
  3717. var x = value1.x - value2.x;
  3718. var y = value1.y - value2.y;
  3719. var z = value1.z - value2.z;
  3720. return (x * x) + (y * y) + (z * z);
  3721. };
  3722. /**
  3723. * Returns a new Vector3 located at the center between "value1" and "value2"
  3724. * @param value1 defines the first operand
  3725. * @param value2 defines the second operand
  3726. * @returns the new Vector3
  3727. */
  3728. Vector3.Center = function (value1, value2) {
  3729. var center = value1.add(value2);
  3730. center.scaleInPlace(0.5);
  3731. return center;
  3732. };
  3733. /**
  3734. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3735. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3736. * to something in order to rotate it from its local system to the given target system
  3737. * Note: axis1, axis2 and axis3 are normalized during this operation
  3738. * @param axis1 defines the first axis
  3739. * @param axis2 defines the second axis
  3740. * @param axis3 defines the third axis
  3741. * @returns a new Vector3
  3742. */
  3743. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3744. var rotation = Vector3.Zero();
  3745. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3746. return rotation;
  3747. };
  3748. /**
  3749. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3750. * @param axis1 defines the first axis
  3751. * @param axis2 defines the second axis
  3752. * @param axis3 defines the third axis
  3753. * @param ref defines the Vector3 where to store the result
  3754. */
  3755. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3756. var quat = MathTmp.Quaternion[0];
  3757. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3758. quat.toEulerAnglesToRef(ref);
  3759. };
  3760. return Vector3;
  3761. }());
  3762. BABYLON.Vector3 = Vector3;
  3763. //Vector4 class created for EulerAngle class conversion to Quaternion
  3764. var Vector4 = /** @class */ (function () {
  3765. /**
  3766. * Creates a Vector4 object from the given floats.
  3767. */
  3768. function Vector4(x, y, z, w) {
  3769. this.x = x;
  3770. this.y = y;
  3771. this.z = z;
  3772. this.w = w;
  3773. }
  3774. /**
  3775. * Returns the string with the Vector4 coordinates.
  3776. */
  3777. Vector4.prototype.toString = function () {
  3778. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3779. };
  3780. /**
  3781. * Returns the string "Vector4".
  3782. */
  3783. Vector4.prototype.getClassName = function () {
  3784. return "Vector4";
  3785. };
  3786. /**
  3787. * Returns the Vector4 hash code.
  3788. */
  3789. Vector4.prototype.getHashCode = function () {
  3790. var hash = this.x || 0;
  3791. hash = (hash * 397) ^ (this.y || 0);
  3792. hash = (hash * 397) ^ (this.z || 0);
  3793. hash = (hash * 397) ^ (this.w || 0);
  3794. return hash;
  3795. };
  3796. // Operators
  3797. /**
  3798. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3799. */
  3800. Vector4.prototype.asArray = function () {
  3801. var result = new Array();
  3802. this.toArray(result, 0);
  3803. return result;
  3804. };
  3805. /**
  3806. * Populates the given array from the given index with the Vector4 coordinates.
  3807. * Returns the Vector4.
  3808. */
  3809. Vector4.prototype.toArray = function (array, index) {
  3810. if (index === undefined) {
  3811. index = 0;
  3812. }
  3813. array[index] = this.x;
  3814. array[index + 1] = this.y;
  3815. array[index + 2] = this.z;
  3816. array[index + 3] = this.w;
  3817. return this;
  3818. };
  3819. /**
  3820. * Adds the given vector to the current Vector4.
  3821. * Returns the updated Vector4.
  3822. */
  3823. Vector4.prototype.addInPlace = function (otherVector) {
  3824. this.x += otherVector.x;
  3825. this.y += otherVector.y;
  3826. this.z += otherVector.z;
  3827. this.w += otherVector.w;
  3828. return this;
  3829. };
  3830. /**
  3831. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3832. */
  3833. Vector4.prototype.add = function (otherVector) {
  3834. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3835. };
  3836. /**
  3837. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3838. * Returns the current Vector4.
  3839. */
  3840. Vector4.prototype.addToRef = function (otherVector, result) {
  3841. result.x = this.x + otherVector.x;
  3842. result.y = this.y + otherVector.y;
  3843. result.z = this.z + otherVector.z;
  3844. result.w = this.w + otherVector.w;
  3845. return this;
  3846. };
  3847. /**
  3848. * Subtract in place the given vector from the current Vector4.
  3849. * Returns the updated Vector4.
  3850. */
  3851. Vector4.prototype.subtractInPlace = function (otherVector) {
  3852. this.x -= otherVector.x;
  3853. this.y -= otherVector.y;
  3854. this.z -= otherVector.z;
  3855. this.w -= otherVector.w;
  3856. return this;
  3857. };
  3858. /**
  3859. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3860. */
  3861. Vector4.prototype.subtract = function (otherVector) {
  3862. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3863. };
  3864. /**
  3865. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3866. * Returns the current Vector4.
  3867. */
  3868. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3869. result.x = this.x - otherVector.x;
  3870. result.y = this.y - otherVector.y;
  3871. result.z = this.z - otherVector.z;
  3872. result.w = this.w - otherVector.w;
  3873. return this;
  3874. };
  3875. /**
  3876. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3877. */
  3878. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3879. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3880. };
  3881. /**
  3882. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3883. * Returns the current Vector4.
  3884. */
  3885. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3886. result.x = this.x - x;
  3887. result.y = this.y - y;
  3888. result.z = this.z - z;
  3889. result.w = this.w - w;
  3890. return this;
  3891. };
  3892. /**
  3893. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3894. */
  3895. Vector4.prototype.negate = function () {
  3896. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3897. };
  3898. /**
  3899. * Multiplies the current Vector4 coordinates by scale (float).
  3900. * Returns the updated Vector4.
  3901. */
  3902. Vector4.prototype.scaleInPlace = function (scale) {
  3903. this.x *= scale;
  3904. this.y *= scale;
  3905. this.z *= scale;
  3906. this.w *= scale;
  3907. return this;
  3908. };
  3909. /**
  3910. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3911. */
  3912. Vector4.prototype.scale = function (scale) {
  3913. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3914. };
  3915. /**
  3916. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3917. * Returns the current Vector4.
  3918. */
  3919. Vector4.prototype.scaleToRef = function (scale, result) {
  3920. result.x = this.x * scale;
  3921. result.y = this.y * scale;
  3922. result.z = this.z * scale;
  3923. result.w = this.w * scale;
  3924. return this;
  3925. };
  3926. /**
  3927. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3928. * @param scale defines the scale factor
  3929. * @param result defines the Vector4 object where to store the result
  3930. * @returns the unmodified current Vector4
  3931. */
  3932. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3933. result.x += this.x * scale;
  3934. result.y += this.y * scale;
  3935. result.z += this.z * scale;
  3936. result.w += this.w * scale;
  3937. return this;
  3938. };
  3939. /**
  3940. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3941. */
  3942. Vector4.prototype.equals = function (otherVector) {
  3943. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3944. };
  3945. /**
  3946. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3947. */
  3948. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3949. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3950. return otherVector
  3951. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3952. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3953. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3954. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3955. };
  3956. /**
  3957. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3958. */
  3959. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3960. return this.x === x && this.y === y && this.z === z && this.w === w;
  3961. };
  3962. /**
  3963. * Multiplies in place the current Vector4 by the given one.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3967. this.x *= otherVector.x;
  3968. this.y *= otherVector.y;
  3969. this.z *= otherVector.z;
  3970. this.w *= otherVector.w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3975. */
  3976. Vector4.prototype.multiply = function (otherVector) {
  3977. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3978. };
  3979. /**
  3980. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3981. * Returns the current Vector4.
  3982. */
  3983. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3984. result.x = this.x * otherVector.x;
  3985. result.y = this.y * otherVector.y;
  3986. result.z = this.z * otherVector.z;
  3987. result.w = this.w * otherVector.w;
  3988. return this;
  3989. };
  3990. /**
  3991. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3992. */
  3993. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3994. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3995. };
  3996. /**
  3997. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3998. */
  3999. Vector4.prototype.divide = function (otherVector) {
  4000. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4001. };
  4002. /**
  4003. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4004. * Returns the current Vector4.
  4005. */
  4006. Vector4.prototype.divideToRef = function (otherVector, result) {
  4007. result.x = this.x / otherVector.x;
  4008. result.y = this.y / otherVector.y;
  4009. result.z = this.z / otherVector.z;
  4010. result.w = this.w / otherVector.w;
  4011. return this;
  4012. };
  4013. /**
  4014. * Divides the current Vector3 coordinates by the given ones.
  4015. * @returns the updated Vector3.
  4016. */
  4017. Vector4.prototype.divideInPlace = function (otherVector) {
  4018. return this.divideToRef(otherVector, this);
  4019. };
  4020. /**
  4021. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4022. * @param other defines the second operand
  4023. * @returns the current updated Vector4
  4024. */
  4025. Vector4.prototype.minimizeInPlace = function (other) {
  4026. if (other.x < this.x)
  4027. this.x = other.x;
  4028. if (other.y < this.y)
  4029. this.y = other.y;
  4030. if (other.z < this.z)
  4031. this.z = other.z;
  4032. if (other.w < this.w)
  4033. this.w = other.w;
  4034. return this;
  4035. };
  4036. /**
  4037. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4038. * @param other defines the second operand
  4039. * @returns the current updated Vector4
  4040. */
  4041. Vector4.prototype.maximizeInPlace = function (other) {
  4042. if (other.x > this.x)
  4043. this.x = other.x;
  4044. if (other.y > this.y)
  4045. this.y = other.y;
  4046. if (other.z > this.z)
  4047. this.z = other.z;
  4048. if (other.w > this.w)
  4049. this.w = other.w;
  4050. return this;
  4051. };
  4052. // Properties
  4053. /**
  4054. * Returns the Vector4 length (float).
  4055. */
  4056. Vector4.prototype.length = function () {
  4057. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4058. };
  4059. /**
  4060. * Returns the Vector4 squared length (float).
  4061. */
  4062. Vector4.prototype.lengthSquared = function () {
  4063. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4064. };
  4065. // Methods
  4066. /**
  4067. * Normalizes in place the Vector4.
  4068. * Returns the updated Vector4.
  4069. */
  4070. Vector4.prototype.normalize = function () {
  4071. var len = this.length();
  4072. if (len === 0)
  4073. return this;
  4074. var num = 1.0 / len;
  4075. this.x *= num;
  4076. this.y *= num;
  4077. this.z *= num;
  4078. this.w *= num;
  4079. return this;
  4080. };
  4081. /**
  4082. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4083. */
  4084. Vector4.prototype.toVector3 = function () {
  4085. return new Vector3(this.x, this.y, this.z);
  4086. };
  4087. /**
  4088. * Returns a new Vector4 copied from the current one.
  4089. */
  4090. Vector4.prototype.clone = function () {
  4091. return new Vector4(this.x, this.y, this.z, this.w);
  4092. };
  4093. /**
  4094. * Updates the current Vector4 with the given one coordinates.
  4095. * Returns the updated Vector4.
  4096. */
  4097. Vector4.prototype.copyFrom = function (source) {
  4098. this.x = source.x;
  4099. this.y = source.y;
  4100. this.z = source.z;
  4101. this.w = source.w;
  4102. return this;
  4103. };
  4104. /**
  4105. * Updates the current Vector4 coordinates with the given floats.
  4106. * Returns the updated Vector4.
  4107. */
  4108. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4109. this.x = x;
  4110. this.y = y;
  4111. this.z = z;
  4112. this.w = w;
  4113. return this;
  4114. };
  4115. /**
  4116. * Updates the current Vector4 coordinates with the given floats.
  4117. * Returns the updated Vector4.
  4118. */
  4119. Vector4.prototype.set = function (x, y, z, w) {
  4120. return this.copyFromFloats(x, y, z, w);
  4121. };
  4122. // Statics
  4123. /**
  4124. * Returns a new Vector4 set from the starting index of the given array.
  4125. */
  4126. Vector4.FromArray = function (array, offset) {
  4127. if (!offset) {
  4128. offset = 0;
  4129. }
  4130. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4131. };
  4132. /**
  4133. * Updates the given vector "result" from the starting index of the given array.
  4134. */
  4135. Vector4.FromArrayToRef = function (array, offset, result) {
  4136. result.x = array[offset];
  4137. result.y = array[offset + 1];
  4138. result.z = array[offset + 2];
  4139. result.w = array[offset + 3];
  4140. };
  4141. /**
  4142. * Updates the given vector "result" from the starting index of the given Float32Array.
  4143. */
  4144. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4145. Vector4.FromArrayToRef(array, offset, result);
  4146. };
  4147. /**
  4148. * Updates the given vector "result" coordinates from the given floats.
  4149. */
  4150. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4151. result.x = x;
  4152. result.y = y;
  4153. result.z = z;
  4154. result.w = w;
  4155. };
  4156. /**
  4157. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4158. */
  4159. Vector4.Zero = function () {
  4160. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4161. };
  4162. /**
  4163. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4164. */
  4165. Vector4.One = function () {
  4166. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4167. };
  4168. /**
  4169. * Returns a new normalized Vector4 from the given one.
  4170. */
  4171. Vector4.Normalize = function (vector) {
  4172. var result = Vector4.Zero();
  4173. Vector4.NormalizeToRef(vector, result);
  4174. return result;
  4175. };
  4176. /**
  4177. * Updates the given vector "result" from the normalization of the given one.
  4178. */
  4179. Vector4.NormalizeToRef = function (vector, result) {
  4180. result.copyFrom(vector);
  4181. result.normalize();
  4182. };
  4183. Vector4.Minimize = function (left, right) {
  4184. var min = left.clone();
  4185. min.minimizeInPlace(right);
  4186. return min;
  4187. };
  4188. Vector4.Maximize = function (left, right) {
  4189. var max = left.clone();
  4190. max.maximizeInPlace(right);
  4191. return max;
  4192. };
  4193. /**
  4194. * Returns the distance (float) between the vectors "value1" and "value2".
  4195. */
  4196. Vector4.Distance = function (value1, value2) {
  4197. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4198. };
  4199. /**
  4200. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4201. */
  4202. Vector4.DistanceSquared = function (value1, value2) {
  4203. var x = value1.x - value2.x;
  4204. var y = value1.y - value2.y;
  4205. var z = value1.z - value2.z;
  4206. var w = value1.w - value2.w;
  4207. return (x * x) + (y * y) + (z * z) + (w * w);
  4208. };
  4209. /**
  4210. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4211. */
  4212. Vector4.Center = function (value1, value2) {
  4213. var center = value1.add(value2);
  4214. center.scaleInPlace(0.5);
  4215. return center;
  4216. };
  4217. /**
  4218. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4219. * This methods computes transformed normalized direction vectors only.
  4220. */
  4221. Vector4.TransformNormal = function (vector, transformation) {
  4222. var result = Vector4.Zero();
  4223. Vector4.TransformNormalToRef(vector, transformation, result);
  4224. return result;
  4225. };
  4226. /**
  4227. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4228. * This methods computes transformed normalized direction vectors only.
  4229. */
  4230. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4231. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4232. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4233. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4234. result.x = x;
  4235. result.y = y;
  4236. result.z = z;
  4237. result.w = vector.w;
  4238. };
  4239. /**
  4240. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4241. * This methods computes transformed normalized direction vectors only.
  4242. */
  4243. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4244. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4245. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4246. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4247. result.w = w;
  4248. };
  4249. return Vector4;
  4250. }());
  4251. BABYLON.Vector4 = Vector4;
  4252. var Size = /** @class */ (function () {
  4253. /**
  4254. * Creates a Size object from the given width and height (floats).
  4255. */
  4256. function Size(width, height) {
  4257. this.width = width;
  4258. this.height = height;
  4259. }
  4260. // Returns a string with the Size width and height.
  4261. Size.prototype.toString = function () {
  4262. return "{W: " + this.width + ", H: " + this.height + "}";
  4263. };
  4264. /**
  4265. * Returns the string "Size"
  4266. */
  4267. Size.prototype.getClassName = function () {
  4268. return "Size";
  4269. };
  4270. /**
  4271. * Returns the Size hash code.
  4272. */
  4273. Size.prototype.getHashCode = function () {
  4274. var hash = this.width || 0;
  4275. hash = (hash * 397) ^ (this.height || 0);
  4276. return hash;
  4277. };
  4278. /**
  4279. * Updates the current size from the given one.
  4280. * Returns the updated Size.
  4281. */
  4282. Size.prototype.copyFrom = function (src) {
  4283. this.width = src.width;
  4284. this.height = src.height;
  4285. };
  4286. /**
  4287. * Updates in place the current Size from the given floats.
  4288. * Returns the updated Size.
  4289. */
  4290. Size.prototype.copyFromFloats = function (width, height) {
  4291. this.width = width;
  4292. this.height = height;
  4293. return this;
  4294. };
  4295. /**
  4296. * Updates in place the current Size from the given floats.
  4297. * Returns the updated Size.
  4298. */
  4299. Size.prototype.set = function (width, height) {
  4300. return this.copyFromFloats(width, height);
  4301. };
  4302. /**
  4303. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4304. */
  4305. Size.prototype.multiplyByFloats = function (w, h) {
  4306. return new Size(this.width * w, this.height * h);
  4307. };
  4308. /**
  4309. * Returns a new Size copied from the given one.
  4310. */
  4311. Size.prototype.clone = function () {
  4312. return new Size(this.width, this.height);
  4313. };
  4314. /**
  4315. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4316. */
  4317. Size.prototype.equals = function (other) {
  4318. if (!other) {
  4319. return false;
  4320. }
  4321. return (this.width === other.width) && (this.height === other.height);
  4322. };
  4323. Object.defineProperty(Size.prototype, "surface", {
  4324. /**
  4325. * Returns the surface of the Size : width * height (float).
  4326. */
  4327. get: function () {
  4328. return this.width * this.height;
  4329. },
  4330. enumerable: true,
  4331. configurable: true
  4332. });
  4333. /**
  4334. * Returns a new Size set to (0.0, 0.0)
  4335. */
  4336. Size.Zero = function () {
  4337. return new Size(0.0, 0.0);
  4338. };
  4339. /**
  4340. * Returns a new Size set as the addition result of the current Size and the given one.
  4341. */
  4342. Size.prototype.add = function (otherSize) {
  4343. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4344. return r;
  4345. };
  4346. /**
  4347. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4348. */
  4349. Size.prototype.subtract = function (otherSize) {
  4350. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4351. return r;
  4352. };
  4353. /**
  4354. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4355. */
  4356. Size.Lerp = function (start, end, amount) {
  4357. var w = start.width + ((end.width - start.width) * amount);
  4358. var h = start.height + ((end.height - start.height) * amount);
  4359. return new Size(w, h);
  4360. };
  4361. return Size;
  4362. }());
  4363. BABYLON.Size = Size;
  4364. /**
  4365. * Class used to store quaternion data
  4366. * @see https://en.wikipedia.org/wiki/Quaternion
  4367. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4368. */
  4369. var Quaternion = /** @class */ (function () {
  4370. /**
  4371. * Creates a new Quaternion from the given floats
  4372. * @param x defines the first component (0 by default)
  4373. * @param y defines the second component (0 by default)
  4374. * @param z defines the third component (0 by default)
  4375. * @param w defines the fourth component (1.0 by default)
  4376. */
  4377. function Quaternion(
  4378. /** defines the first component (0 by default) */
  4379. x,
  4380. /** defines the second component (0 by default) */
  4381. y,
  4382. /** defines the third component (0 by default) */
  4383. z,
  4384. /** defines the fourth component (1.0 by default) */
  4385. w) {
  4386. if (x === void 0) { x = 0.0; }
  4387. if (y === void 0) { y = 0.0; }
  4388. if (z === void 0) { z = 0.0; }
  4389. if (w === void 0) { w = 1.0; }
  4390. this.x = x;
  4391. this.y = y;
  4392. this.z = z;
  4393. this.w = w;
  4394. }
  4395. /**
  4396. * Gets a string representation for the current quaternion
  4397. * @returns a string with the Quaternion coordinates
  4398. */
  4399. Quaternion.prototype.toString = function () {
  4400. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4401. };
  4402. /**
  4403. * Gets the class name of the quaternion
  4404. * @returns the string "Quaternion"
  4405. */
  4406. Quaternion.prototype.getClassName = function () {
  4407. return "Quaternion";
  4408. };
  4409. /**
  4410. * Gets a hash code for this quaternion
  4411. * @returns the quaternion hash code
  4412. */
  4413. Quaternion.prototype.getHashCode = function () {
  4414. var hash = this.x || 0;
  4415. hash = (hash * 397) ^ (this.y || 0);
  4416. hash = (hash * 397) ^ (this.z || 0);
  4417. hash = (hash * 397) ^ (this.w || 0);
  4418. return hash;
  4419. };
  4420. /**
  4421. * Copy the quaternion to an array
  4422. * @returns a new array populated with 4 elements from the quaternion coordinates
  4423. */
  4424. Quaternion.prototype.asArray = function () {
  4425. return [this.x, this.y, this.z, this.w];
  4426. };
  4427. /**
  4428. * Check if two quaternions are equals
  4429. * @param otherQuaternion defines the second operand
  4430. * @return true if the current quaternion and the given one coordinates are strictly equals
  4431. */
  4432. Quaternion.prototype.equals = function (otherQuaternion) {
  4433. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4434. };
  4435. /**
  4436. * Clone the current quaternion
  4437. * @returns a new quaternion copied from the current one
  4438. */
  4439. Quaternion.prototype.clone = function () {
  4440. return new Quaternion(this.x, this.y, this.z, this.w);
  4441. };
  4442. /**
  4443. * Copy a quaternion to the current one
  4444. * @param other defines the other quaternion
  4445. * @returns the updated current quaternion
  4446. */
  4447. Quaternion.prototype.copyFrom = function (other) {
  4448. this.x = other.x;
  4449. this.y = other.y;
  4450. this.z = other.z;
  4451. this.w = other.w;
  4452. return this;
  4453. };
  4454. /**
  4455. * Updates the current quaternion with the given float coordinates
  4456. * @param x defines the x coordinate
  4457. * @param y defines the y coordinate
  4458. * @param z defines the z coordinate
  4459. * @param w defines the w coordinate
  4460. * @returns the updated current quaternion
  4461. */
  4462. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4463. this.x = x;
  4464. this.y = y;
  4465. this.z = z;
  4466. this.w = w;
  4467. return this;
  4468. };
  4469. /**
  4470. * Updates the current quaternion from the given float coordinates
  4471. * @param x defines the x coordinate
  4472. * @param y defines the y coordinate
  4473. * @param z defines the z coordinate
  4474. * @param w defines the w coordinate
  4475. * @returns the updated current quaternion
  4476. */
  4477. Quaternion.prototype.set = function (x, y, z, w) {
  4478. return this.copyFromFloats(x, y, z, w);
  4479. };
  4480. /**
  4481. * Adds two quaternions
  4482. * @param other defines the second operand
  4483. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4484. */
  4485. Quaternion.prototype.add = function (other) {
  4486. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4487. };
  4488. /**
  4489. * Add a quaternion to the current one
  4490. * @param other defines the quaternion to add
  4491. * @returns the current quaternion
  4492. */
  4493. Quaternion.prototype.addInPlace = function (other) {
  4494. this.x += other.x;
  4495. this.y += other.y;
  4496. this.z += other.z;
  4497. this.w += other.w;
  4498. return this;
  4499. };
  4500. /**
  4501. * Subtract two quaternions
  4502. * @param other defines the second operand
  4503. * @returns a new quaternion as the subtraction result of the given one from the current one
  4504. */
  4505. Quaternion.prototype.subtract = function (other) {
  4506. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4507. };
  4508. /**
  4509. * Multiplies the current quaternion by a scale factor
  4510. * @param value defines the scale factor
  4511. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4512. */
  4513. Quaternion.prototype.scale = function (value) {
  4514. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4515. };
  4516. /**
  4517. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4518. * @param scale defines the scale factor
  4519. * @param result defines the Quaternion object where to store the result
  4520. * @returns the unmodified current quaternion
  4521. */
  4522. Quaternion.prototype.scaleToRef = function (scale, result) {
  4523. result.x = this.x * scale;
  4524. result.y = this.y * scale;
  4525. result.z = this.z * scale;
  4526. result.w = this.w * scale;
  4527. return this;
  4528. };
  4529. /**
  4530. * Multiplies in place the current quaternion by a scale factor
  4531. * @param value defines the scale factor
  4532. * @returns the current modified quaternion
  4533. */
  4534. Quaternion.prototype.scaleInPlace = function (value) {
  4535. this.x *= value;
  4536. this.y *= value;
  4537. this.z *= value;
  4538. this.w *= value;
  4539. return this;
  4540. };
  4541. /**
  4542. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4543. * @param scale defines the scale factor
  4544. * @param result defines the Quaternion object where to store the result
  4545. * @returns the unmodified current quaternion
  4546. */
  4547. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4548. result.x += this.x * scale;
  4549. result.y += this.y * scale;
  4550. result.z += this.z * scale;
  4551. result.w += this.w * scale;
  4552. return this;
  4553. };
  4554. /**
  4555. * Multiplies two quaternions
  4556. * @param q1 defines the second operand
  4557. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4558. */
  4559. Quaternion.prototype.multiply = function (q1) {
  4560. var result = new Quaternion(0, 0, 0, 1.0);
  4561. this.multiplyToRef(q1, result);
  4562. return result;
  4563. };
  4564. /**
  4565. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @param result defines the target quaternion
  4568. * @returns the current quaternion
  4569. */
  4570. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4571. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4572. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4573. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4574. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4575. result.copyFromFloats(x, y, z, w);
  4576. return this;
  4577. };
  4578. /**
  4579. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4580. * @param q1 defines the second operand
  4581. * @returns the currentupdated quaternion
  4582. */
  4583. Quaternion.prototype.multiplyInPlace = function (q1) {
  4584. this.multiplyToRef(q1, this);
  4585. return this;
  4586. };
  4587. /**
  4588. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4589. * @param ref defines the target quaternion
  4590. * @returns the current quaternion
  4591. */
  4592. Quaternion.prototype.conjugateToRef = function (ref) {
  4593. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4594. return this;
  4595. };
  4596. /**
  4597. * Conjugates in place (1-q) the current quaternion
  4598. * @returns the current updated quaternion
  4599. */
  4600. Quaternion.prototype.conjugateInPlace = function () {
  4601. this.x *= -1;
  4602. this.y *= -1;
  4603. this.z *= -1;
  4604. return this;
  4605. };
  4606. /**
  4607. * Conjugates in place (1-q) the current quaternion
  4608. * @returns a new quaternion
  4609. */
  4610. Quaternion.prototype.conjugate = function () {
  4611. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4612. return result;
  4613. };
  4614. /**
  4615. * Gets length of current quaternion
  4616. * @returns the quaternion length (float)
  4617. */
  4618. Quaternion.prototype.length = function () {
  4619. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4620. };
  4621. /**
  4622. * Normalize in place the current quaternion
  4623. * @returns the current updated quaternion
  4624. */
  4625. Quaternion.prototype.normalize = function () {
  4626. var length = 1.0 / this.length();
  4627. this.x *= length;
  4628. this.y *= length;
  4629. this.z *= length;
  4630. this.w *= length;
  4631. return this;
  4632. };
  4633. /**
  4634. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4635. * @param order is a reserved parameter and is ignore for now
  4636. * @returns a new Vector3 containing the Euler angles
  4637. */
  4638. Quaternion.prototype.toEulerAngles = function (order) {
  4639. if (order === void 0) { order = "YZX"; }
  4640. var result = Vector3.Zero();
  4641. this.toEulerAnglesToRef(result, order);
  4642. return result;
  4643. };
  4644. /**
  4645. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4646. * @param result defines the vector which will be filled with the Euler angles
  4647. * @param order is a reserved parameter and is ignore for now
  4648. * @returns the current unchanged quaternion
  4649. */
  4650. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4651. if (order === void 0) { order = "YZX"; }
  4652. var qz = this.z;
  4653. var qx = this.x;
  4654. var qy = this.y;
  4655. var qw = this.w;
  4656. var sqw = qw * qw;
  4657. var sqz = qz * qz;
  4658. var sqx = qx * qx;
  4659. var sqy = qy * qy;
  4660. var zAxisY = qy * qz - qx * qw;
  4661. var limit = .4999999;
  4662. if (zAxisY < -limit) {
  4663. result.y = 2 * Math.atan2(qy, qw);
  4664. result.x = Math.PI / 2;
  4665. result.z = 0;
  4666. }
  4667. else if (zAxisY > limit) {
  4668. result.y = 2 * Math.atan2(qy, qw);
  4669. result.x = -Math.PI / 2;
  4670. result.z = 0;
  4671. }
  4672. else {
  4673. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4674. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4675. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4676. }
  4677. return this;
  4678. };
  4679. /**
  4680. * Updates the given rotation matrix with the current quaternion values
  4681. * @param result defines the target matrix
  4682. * @returns the current unchanged quaternion
  4683. */
  4684. Quaternion.prototype.toRotationMatrix = function (result) {
  4685. var xx = this.x * this.x;
  4686. var yy = this.y * this.y;
  4687. var zz = this.z * this.z;
  4688. var xy = this.x * this.y;
  4689. var zw = this.z * this.w;
  4690. var zx = this.z * this.x;
  4691. var yw = this.y * this.w;
  4692. var yz = this.y * this.z;
  4693. var xw = this.x * this.w;
  4694. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4695. result.m[1] = 2.0 * (xy + zw);
  4696. result.m[2] = 2.0 * (zx - yw);
  4697. result.m[3] = 0;
  4698. result.m[4] = 2.0 * (xy - zw);
  4699. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4700. result.m[6] = 2.0 * (yz + xw);
  4701. result.m[7] = 0;
  4702. result.m[8] = 2.0 * (zx + yw);
  4703. result.m[9] = 2.0 * (yz - xw);
  4704. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4705. result.m[11] = 0;
  4706. result.m[12] = 0;
  4707. result.m[13] = 0;
  4708. result.m[14] = 0;
  4709. result.m[15] = 1.0;
  4710. result._markAsUpdated();
  4711. return this;
  4712. };
  4713. /**
  4714. * Updates the current quaternion from the given rotation matrix values
  4715. * @param matrix defines the source matrix
  4716. * @returns the current updated quaternion
  4717. */
  4718. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4719. Quaternion.FromRotationMatrixToRef(matrix, this);
  4720. return this;
  4721. };
  4722. // Statics
  4723. /**
  4724. * Creates a new quaternion from a rotation matrix
  4725. * @param matrix defines the source matrix
  4726. * @returns a new quaternion created from the given rotation matrix values
  4727. */
  4728. Quaternion.FromRotationMatrix = function (matrix) {
  4729. var result = new Quaternion();
  4730. Quaternion.FromRotationMatrixToRef(matrix, result);
  4731. return result;
  4732. };
  4733. /**
  4734. * Updates the given quaternion with the given rotation matrix values
  4735. * @param matrix defines the source matrix
  4736. * @param result defines the target quaternion
  4737. */
  4738. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4739. var data = matrix.m;
  4740. var m11 = data[0], m12 = data[4], m13 = data[8];
  4741. var m21 = data[1], m22 = data[5], m23 = data[9];
  4742. var m31 = data[2], m32 = data[6], m33 = data[10];
  4743. var trace = m11 + m22 + m33;
  4744. var s;
  4745. if (trace > 0) {
  4746. s = 0.5 / Math.sqrt(trace + 1.0);
  4747. result.w = 0.25 / s;
  4748. result.x = (m32 - m23) * s;
  4749. result.y = (m13 - m31) * s;
  4750. result.z = (m21 - m12) * s;
  4751. }
  4752. else if (m11 > m22 && m11 > m33) {
  4753. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4754. result.w = (m32 - m23) / s;
  4755. result.x = 0.25 * s;
  4756. result.y = (m12 + m21) / s;
  4757. result.z = (m13 + m31) / s;
  4758. }
  4759. else if (m22 > m33) {
  4760. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4761. result.w = (m13 - m31) / s;
  4762. result.x = (m12 + m21) / s;
  4763. result.y = 0.25 * s;
  4764. result.z = (m23 + m32) / s;
  4765. }
  4766. else {
  4767. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4768. result.w = (m21 - m12) / s;
  4769. result.x = (m13 + m31) / s;
  4770. result.y = (m23 + m32) / s;
  4771. result.z = 0.25 * s;
  4772. }
  4773. };
  4774. /**
  4775. * Returns the dot product (float) between the quaternions "left" and "right"
  4776. * @param left defines the left operand
  4777. * @param right defines the right operand
  4778. * @returns the dot product
  4779. */
  4780. Quaternion.Dot = function (left, right) {
  4781. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4782. };
  4783. /**
  4784. * Checks if the two quaternions are close to each other
  4785. * @param quat0 defines the first quaternion to check
  4786. * @param quat1 defines the second quaternion to check
  4787. * @returns true if the two quaternions are close to each other
  4788. */
  4789. Quaternion.AreClose = function (quat0, quat1) {
  4790. var dot = Quaternion.Dot(quat0, quat1);
  4791. return dot >= 0;
  4792. };
  4793. /**
  4794. * Creates an empty quaternion
  4795. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4796. */
  4797. Quaternion.Zero = function () {
  4798. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4799. };
  4800. /**
  4801. * Inverse a given quaternion
  4802. * @param q defines the source quaternion
  4803. * @returns a new quaternion as the inverted current quaternion
  4804. */
  4805. Quaternion.Inverse = function (q) {
  4806. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4807. };
  4808. /**
  4809. * Creates an identity quaternion
  4810. * @returns the identity quaternion
  4811. */
  4812. Quaternion.Identity = function () {
  4813. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4814. };
  4815. /**
  4816. * Gets a boolean indicating if the given quaternion is identity
  4817. * @param quaternion defines the quaternion to check
  4818. * @returns true if the quaternion is identity
  4819. */
  4820. Quaternion.IsIdentity = function (quaternion) {
  4821. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4822. };
  4823. /**
  4824. * Creates a quaternion from a rotation around an axis
  4825. * @param axis defines the axis to use
  4826. * @param angle defines the angle to use
  4827. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4828. */
  4829. Quaternion.RotationAxis = function (axis, angle) {
  4830. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4831. };
  4832. /**
  4833. * Creates a rotation around an axis and stores it into the given quaternion
  4834. * @param axis defines the axis to use
  4835. * @param angle defines the angle to use
  4836. * @param result defines the target quaternion
  4837. * @returns the target quaternion
  4838. */
  4839. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4840. var sin = Math.sin(angle / 2);
  4841. axis.normalize();
  4842. result.w = Math.cos(angle / 2);
  4843. result.x = axis.x * sin;
  4844. result.y = axis.y * sin;
  4845. result.z = axis.z * sin;
  4846. return result;
  4847. };
  4848. /**
  4849. * Creates a new quaternion from data stored into an array
  4850. * @param array defines the data source
  4851. * @param offset defines the offset in the source array where the data starts
  4852. * @returns a new quaternion
  4853. */
  4854. Quaternion.FromArray = function (array, offset) {
  4855. if (!offset) {
  4856. offset = 0;
  4857. }
  4858. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4859. };
  4860. /**
  4861. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4862. * @param yaw defines the rotation around Y axis
  4863. * @param pitch defines the rotation around X axis
  4864. * @param roll defines the rotation around Z axis
  4865. * @returns the new quaternion
  4866. */
  4867. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4868. var q = new Quaternion();
  4869. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4870. return q;
  4871. };
  4872. /**
  4873. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4874. * @param yaw defines the rotation around Y axis
  4875. * @param pitch defines the rotation around X axis
  4876. * @param roll defines the rotation around Z axis
  4877. * @param result defines the target quaternion
  4878. */
  4879. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4880. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4881. var halfRoll = roll * 0.5;
  4882. var halfPitch = pitch * 0.5;
  4883. var halfYaw = yaw * 0.5;
  4884. var sinRoll = Math.sin(halfRoll);
  4885. var cosRoll = Math.cos(halfRoll);
  4886. var sinPitch = Math.sin(halfPitch);
  4887. var cosPitch = Math.cos(halfPitch);
  4888. var sinYaw = Math.sin(halfYaw);
  4889. var cosYaw = Math.cos(halfYaw);
  4890. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4891. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4892. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4893. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4894. };
  4895. /**
  4896. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4897. * @param alpha defines the rotation around first axis
  4898. * @param beta defines the rotation around second axis
  4899. * @param gamma defines the rotation around third axis
  4900. * @returns the new quaternion
  4901. */
  4902. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4903. var result = new Quaternion();
  4904. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4905. return result;
  4906. };
  4907. /**
  4908. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4909. * @param alpha defines the rotation around first axis
  4910. * @param beta defines the rotation around second axis
  4911. * @param gamma defines the rotation around third axis
  4912. * @param result defines the target quaternion
  4913. */
  4914. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4915. // Produces a quaternion from Euler angles in the z-x-z orientation
  4916. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4917. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4918. var halfBeta = beta * 0.5;
  4919. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4920. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4921. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4922. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4923. };
  4924. /**
  4925. * 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)
  4926. * @param axis1 defines the first axis
  4927. * @param axis2 defines the second axis
  4928. * @param axis3 defines the third axis
  4929. * @returns the new quaternion
  4930. */
  4931. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4932. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4933. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4934. return quat;
  4935. };
  4936. /**
  4937. * 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
  4938. * @param axis1 defines the first axis
  4939. * @param axis2 defines the second axis
  4940. * @param axis3 defines the third axis
  4941. * @param ref defines the target quaternion
  4942. */
  4943. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4944. var rotMat = MathTmp.Matrix[0];
  4945. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4946. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4947. };
  4948. /**
  4949. * Interpolates between two quaternions
  4950. * @param left defines first quaternion
  4951. * @param right defines second quaternion
  4952. * @param amount defines the gradient to use
  4953. * @returns the new interpolated quaternion
  4954. */
  4955. Quaternion.Slerp = function (left, right, amount) {
  4956. var result = Quaternion.Identity();
  4957. Quaternion.SlerpToRef(left, right, amount, result);
  4958. return result;
  4959. };
  4960. /**
  4961. * Interpolates between two quaternions and stores it into a target quaternion
  4962. * @param left defines first quaternion
  4963. * @param right defines second quaternion
  4964. * @param amount defines the gradient to use
  4965. * @param result defines the target quaternion
  4966. */
  4967. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4968. var num2;
  4969. var num3;
  4970. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4971. var flag = false;
  4972. if (num4 < 0) {
  4973. flag = true;
  4974. num4 = -num4;
  4975. }
  4976. if (num4 > 0.999999) {
  4977. num3 = 1 - amount;
  4978. num2 = flag ? -amount : amount;
  4979. }
  4980. else {
  4981. var num5 = Math.acos(num4);
  4982. var num6 = (1.0 / Math.sin(num5));
  4983. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4984. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4985. }
  4986. result.x = (num3 * left.x) + (num2 * right.x);
  4987. result.y = (num3 * left.y) + (num2 * right.y);
  4988. result.z = (num3 * left.z) + (num2 * right.z);
  4989. result.w = (num3 * left.w) + (num2 * right.w);
  4990. };
  4991. /**
  4992. * Interpolate between two quaternions using Hermite interpolation
  4993. * @param value1 defines first quaternion
  4994. * @param tangent1 defines the incoming tangent
  4995. * @param value2 defines second quaternion
  4996. * @param tangent2 defines the outgoing tangent
  4997. * @param amount defines the target quaternion
  4998. * @returns the new interpolated quaternion
  4999. */
  5000. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5001. var squared = amount * amount;
  5002. var cubed = amount * squared;
  5003. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5004. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5005. var part3 = (cubed - (2.0 * squared)) + amount;
  5006. var part4 = cubed - squared;
  5007. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5008. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5009. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5010. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5011. return new Quaternion(x, y, z, w);
  5012. };
  5013. return Quaternion;
  5014. }());
  5015. BABYLON.Quaternion = Quaternion;
  5016. /**
  5017. * Class used to store matrix data (4x4)
  5018. */
  5019. var Matrix = /** @class */ (function () {
  5020. /**
  5021. * Creates an empty matrix (filled with zeros)
  5022. */
  5023. function Matrix() {
  5024. this._isIdentity = false;
  5025. this._isIdentityDirty = true;
  5026. /**
  5027. * Gets or sets the internal data of the matrix
  5028. */
  5029. this.m = new Float32Array(16);
  5030. this._markAsUpdated();
  5031. }
  5032. /** @hidden */
  5033. Matrix.prototype._markAsUpdated = function () {
  5034. this.updateFlag = Matrix._updateFlagSeed++;
  5035. this._isIdentityDirty = true;
  5036. };
  5037. // Properties
  5038. /**
  5039. * Check if the current matrix is indentity
  5040. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5041. * @returns true is the matrix is the identity matrix
  5042. */
  5043. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5044. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5045. if (this._isIdentityDirty) {
  5046. this._isIdentityDirty = false;
  5047. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5048. this._isIdentity = false;
  5049. }
  5050. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5051. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5052. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5053. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5054. this._isIdentity = false;
  5055. }
  5056. else {
  5057. this._isIdentity = true;
  5058. }
  5059. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5060. this._isIdentity = false;
  5061. }
  5062. }
  5063. return this._isIdentity;
  5064. };
  5065. /**
  5066. * Gets the determinant of the matrix
  5067. * @returns the matrix determinant
  5068. */
  5069. Matrix.prototype.determinant = function () {
  5070. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5071. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5072. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5073. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5074. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5075. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5076. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5077. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5078. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5079. };
  5080. // Methods
  5081. /**
  5082. * Returns the matrix as a Float32Array
  5083. * @returns the matrix underlying array
  5084. */
  5085. Matrix.prototype.toArray = function () {
  5086. return this.m;
  5087. };
  5088. /**
  5089. * Returns the matrix as a Float32Array
  5090. * @returns the matrix underlying array.
  5091. */
  5092. Matrix.prototype.asArray = function () {
  5093. return this.toArray();
  5094. };
  5095. /**
  5096. * Inverts the current matrix in place
  5097. * @returns the current inverted matrix
  5098. */
  5099. Matrix.prototype.invert = function () {
  5100. this.invertToRef(this);
  5101. return this;
  5102. };
  5103. /**
  5104. * Sets all the matrix elements to zero
  5105. * @returns the current matrix
  5106. */
  5107. Matrix.prototype.reset = function () {
  5108. for (var index = 0; index < 16; index++) {
  5109. this.m[index] = 0.0;
  5110. }
  5111. this._markAsUpdated();
  5112. return this;
  5113. };
  5114. /**
  5115. * Adds the current matrix with a second one
  5116. * @param other defines the matrix to add
  5117. * @returns a new matrix as the addition of the current matrix and the given one
  5118. */
  5119. Matrix.prototype.add = function (other) {
  5120. var result = new Matrix();
  5121. this.addToRef(other, result);
  5122. return result;
  5123. };
  5124. /**
  5125. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5126. * @param other defines the matrix to add
  5127. * @param result defines the target matrix
  5128. * @returns the current matrix
  5129. */
  5130. Matrix.prototype.addToRef = function (other, result) {
  5131. for (var index = 0; index < 16; index++) {
  5132. result.m[index] = this.m[index] + other.m[index];
  5133. }
  5134. result._markAsUpdated();
  5135. return this;
  5136. };
  5137. /**
  5138. * Adds in place the given matrix to the current matrix
  5139. * @param other defines the second operand
  5140. * @returns the current updated matrix
  5141. */
  5142. Matrix.prototype.addToSelf = function (other) {
  5143. for (var index = 0; index < 16; index++) {
  5144. this.m[index] += other.m[index];
  5145. }
  5146. this._markAsUpdated();
  5147. return this;
  5148. };
  5149. /**
  5150. * Sets the given matrix to the current inverted Matrix
  5151. * @param other defines the target matrix
  5152. * @returns the unmodified current matrix
  5153. */
  5154. Matrix.prototype.invertToRef = function (other) {
  5155. var l1 = this.m[0];
  5156. var l2 = this.m[1];
  5157. var l3 = this.m[2];
  5158. var l4 = this.m[3];
  5159. var l5 = this.m[4];
  5160. var l6 = this.m[5];
  5161. var l7 = this.m[6];
  5162. var l8 = this.m[7];
  5163. var l9 = this.m[8];
  5164. var l10 = this.m[9];
  5165. var l11 = this.m[10];
  5166. var l12 = this.m[11];
  5167. var l13 = this.m[12];
  5168. var l14 = this.m[13];
  5169. var l15 = this.m[14];
  5170. var l16 = this.m[15];
  5171. var l17 = (l11 * l16) - (l12 * l15);
  5172. var l18 = (l10 * l16) - (l12 * l14);
  5173. var l19 = (l10 * l15) - (l11 * l14);
  5174. var l20 = (l9 * l16) - (l12 * l13);
  5175. var l21 = (l9 * l15) - (l11 * l13);
  5176. var l22 = (l9 * l14) - (l10 * l13);
  5177. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5178. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5179. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5180. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5181. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5182. var l28 = (l7 * l16) - (l8 * l15);
  5183. var l29 = (l6 * l16) - (l8 * l14);
  5184. var l30 = (l6 * l15) - (l7 * l14);
  5185. var l31 = (l5 * l16) - (l8 * l13);
  5186. var l32 = (l5 * l15) - (l7 * l13);
  5187. var l33 = (l5 * l14) - (l6 * l13);
  5188. var l34 = (l7 * l12) - (l8 * l11);
  5189. var l35 = (l6 * l12) - (l8 * l10);
  5190. var l36 = (l6 * l11) - (l7 * l10);
  5191. var l37 = (l5 * l12) - (l8 * l9);
  5192. var l38 = (l5 * l11) - (l7 * l9);
  5193. var l39 = (l5 * l10) - (l6 * l9);
  5194. other.m[0] = l23 * l27;
  5195. other.m[4] = l24 * l27;
  5196. other.m[8] = l25 * l27;
  5197. other.m[12] = l26 * l27;
  5198. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5199. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5200. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5201. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5202. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5203. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5204. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5205. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5206. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5207. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5208. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5209. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5210. other._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector (using 3 floats) in the current matrix
  5215. * @param x defines the 1st component of the translation
  5216. * @param y defines the 2nd component of the translation
  5217. * @param z defines the 3rd component of the translation
  5218. * @returns the current updated matrix
  5219. */
  5220. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5221. this.m[12] = x;
  5222. this.m[13] = y;
  5223. this.m[14] = z;
  5224. this._markAsUpdated();
  5225. return this;
  5226. };
  5227. /**
  5228. * Inserts the translation vector in the current matrix
  5229. * @param vector3 defines the translation to insert
  5230. * @returns the current updated matrix
  5231. */
  5232. Matrix.prototype.setTranslation = function (vector3) {
  5233. this.m[12] = vector3.x;
  5234. this.m[13] = vector3.y;
  5235. this.m[14] = vector3.z;
  5236. this._markAsUpdated();
  5237. return this;
  5238. };
  5239. /**
  5240. * Gets the translation value of the current matrix
  5241. * @returns a new Vector3 as the extracted translation from the matrix
  5242. */
  5243. Matrix.prototype.getTranslation = function () {
  5244. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5245. };
  5246. /**
  5247. * Fill a Vector3 with the extracted translation from the matrix
  5248. * @param result defines the Vector3 where to store the translation
  5249. * @returns the current matrix
  5250. */
  5251. Matrix.prototype.getTranslationToRef = function (result) {
  5252. result.x = this.m[12];
  5253. result.y = this.m[13];
  5254. result.z = this.m[14];
  5255. return this;
  5256. };
  5257. /**
  5258. * Remove rotation and scaling part from the matrix
  5259. * @returns the updated matrix
  5260. */
  5261. Matrix.prototype.removeRotationAndScaling = function () {
  5262. this.setRowFromFloats(0, 1, 0, 0, 0);
  5263. this.setRowFromFloats(1, 0, 1, 0, 0);
  5264. this.setRowFromFloats(2, 0, 0, 1, 0);
  5265. return this;
  5266. };
  5267. /**
  5268. * Multiply two matrices
  5269. * @param other defines the second operand
  5270. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5271. */
  5272. Matrix.prototype.multiply = function (other) {
  5273. var result = new Matrix();
  5274. this.multiplyToRef(other, result);
  5275. return result;
  5276. };
  5277. /**
  5278. * Copy the current matrix from the given one
  5279. * @param other defines the source matrix
  5280. * @returns the current updated matrix
  5281. */
  5282. Matrix.prototype.copyFrom = function (other) {
  5283. for (var index = 0; index < 16; index++) {
  5284. this.m[index] = other.m[index];
  5285. }
  5286. this._markAsUpdated();
  5287. return this;
  5288. };
  5289. /**
  5290. * Populates the given array from the starting index with the current matrix values
  5291. * @param array defines the target array
  5292. * @param offset defines the offset in the target array where to start storing values
  5293. * @returns the current matrix
  5294. */
  5295. Matrix.prototype.copyToArray = function (array, offset) {
  5296. if (offset === void 0) { offset = 0; }
  5297. for (var index = 0; index < 16; index++) {
  5298. array[offset + index] = this.m[index];
  5299. }
  5300. return this;
  5301. };
  5302. /**
  5303. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5304. * @param other defines the second operand
  5305. * @param result defines the matrix where to store the multiplication
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.multiplyToRef = function (other, result) {
  5309. this.multiplyToArray(other, result.m, 0);
  5310. result._markAsUpdated();
  5311. return this;
  5312. };
  5313. /**
  5314. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5315. * @param other defines the second operand
  5316. * @param result defines the array where to store the multiplication
  5317. * @param offset defines the offset in the target array where to start storing values
  5318. * @returns the current matrix
  5319. */
  5320. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5321. var tm0 = this.m[0];
  5322. var tm1 = this.m[1];
  5323. var tm2 = this.m[2];
  5324. var tm3 = this.m[3];
  5325. var tm4 = this.m[4];
  5326. var tm5 = this.m[5];
  5327. var tm6 = this.m[6];
  5328. var tm7 = this.m[7];
  5329. var tm8 = this.m[8];
  5330. var tm9 = this.m[9];
  5331. var tm10 = this.m[10];
  5332. var tm11 = this.m[11];
  5333. var tm12 = this.m[12];
  5334. var tm13 = this.m[13];
  5335. var tm14 = this.m[14];
  5336. var tm15 = this.m[15];
  5337. var om0 = other.m[0];
  5338. var om1 = other.m[1];
  5339. var om2 = other.m[2];
  5340. var om3 = other.m[3];
  5341. var om4 = other.m[4];
  5342. var om5 = other.m[5];
  5343. var om6 = other.m[6];
  5344. var om7 = other.m[7];
  5345. var om8 = other.m[8];
  5346. var om9 = other.m[9];
  5347. var om10 = other.m[10];
  5348. var om11 = other.m[11];
  5349. var om12 = other.m[12];
  5350. var om13 = other.m[13];
  5351. var om14 = other.m[14];
  5352. var om15 = other.m[15];
  5353. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5354. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5355. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5356. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5357. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5358. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5359. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5360. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5361. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5362. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5363. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5364. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5365. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5366. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5367. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5368. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5369. return this;
  5370. };
  5371. /**
  5372. * Check equality between this matrix and a second one
  5373. * @param value defines the second matrix to compare
  5374. * @returns true is the current matrix and the given one values are strictly equal
  5375. */
  5376. Matrix.prototype.equals = function (value) {
  5377. return value &&
  5378. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5379. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5380. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5381. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5382. };
  5383. /**
  5384. * Clone the current matrix
  5385. * @returns a new matrix from the current matrix
  5386. */
  5387. Matrix.prototype.clone = function () {
  5388. 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]);
  5389. };
  5390. /**
  5391. * Returns the name of the current matrix class
  5392. * @returns the string "Matrix"
  5393. */
  5394. Matrix.prototype.getClassName = function () {
  5395. return "Matrix";
  5396. };
  5397. /**
  5398. * Gets the hash code of the current matrix
  5399. * @returns the hash code
  5400. */
  5401. Matrix.prototype.getHashCode = function () {
  5402. var hash = this.m[0] || 0;
  5403. for (var i = 1; i < 16; i++) {
  5404. hash = (hash * 397) ^ (this.m[i] || 0);
  5405. }
  5406. return hash;
  5407. };
  5408. /**
  5409. * Decomposes the current Matrix into a translation, rotation and scaling components
  5410. * @param scale defines the scale vector3 given as a reference to update
  5411. * @param rotation defines the rotation quaternion given as a reference to update
  5412. * @param translation defines the translation vector3 given as a reference to update
  5413. * @returns true if operation was successful
  5414. */
  5415. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5416. if (translation) {
  5417. translation.x = this.m[12];
  5418. translation.y = this.m[13];
  5419. translation.z = this.m[14];
  5420. }
  5421. scale = scale || MathTmp.Vector3[0];
  5422. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5423. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5424. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5425. if (this.determinant() <= 0) {
  5426. scale.y *= -1;
  5427. }
  5428. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5429. if (rotation) {
  5430. rotation.x = 0;
  5431. rotation.y = 0;
  5432. rotation.z = 0;
  5433. rotation.w = 1;
  5434. }
  5435. return false;
  5436. }
  5437. if (rotation) {
  5438. 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]);
  5439. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5440. }
  5441. return true;
  5442. };
  5443. /**
  5444. * Gets specific row of the matrix
  5445. * @param index defines the number of the row to get
  5446. * @returns the index-th row of the current matrix as a new Vector4
  5447. */
  5448. Matrix.prototype.getRow = function (index) {
  5449. if (index < 0 || index > 3) {
  5450. return null;
  5451. }
  5452. var i = index * 4;
  5453. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5454. };
  5455. /**
  5456. * Sets the index-th row of the current matrix to the vector4 values
  5457. * @param index defines the number of the row to set
  5458. * @param row defines the target vector4
  5459. * @returns the updated current matrix
  5460. */
  5461. Matrix.prototype.setRow = function (index, row) {
  5462. if (index < 0 || index > 3) {
  5463. return this;
  5464. }
  5465. var i = index * 4;
  5466. this.m[i + 0] = row.x;
  5467. this.m[i + 1] = row.y;
  5468. this.m[i + 2] = row.z;
  5469. this.m[i + 3] = row.w;
  5470. this._markAsUpdated();
  5471. return this;
  5472. };
  5473. /**
  5474. * Compute the transpose of the matrix
  5475. * @returns the new transposed matrix
  5476. */
  5477. Matrix.prototype.transpose = function () {
  5478. return Matrix.Transpose(this);
  5479. };
  5480. /**
  5481. * Compute the transpose of the matrix and store it in a given matrix
  5482. * @param result defines the target matrix
  5483. * @returns the current matrix
  5484. */
  5485. Matrix.prototype.transposeToRef = function (result) {
  5486. Matrix.TransposeToRef(this, result);
  5487. return this;
  5488. };
  5489. /**
  5490. * Sets the index-th row of the current matrix with the given 4 x float values
  5491. * @param index defines the row index
  5492. * @param x defines the x component to set
  5493. * @param y defines the y component to set
  5494. * @param z defines the z component to set
  5495. * @param w defines the w component to set
  5496. * @returns the updated current matrix
  5497. */
  5498. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5499. if (index < 0 || index > 3) {
  5500. return this;
  5501. }
  5502. var i = index * 4;
  5503. this.m[i + 0] = x;
  5504. this.m[i + 1] = y;
  5505. this.m[i + 2] = z;
  5506. this.m[i + 3] = w;
  5507. this._markAsUpdated();
  5508. return this;
  5509. };
  5510. /**
  5511. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5512. * @param scale defines the scale factor
  5513. * @returns a new matrix
  5514. */
  5515. Matrix.prototype.scale = function (scale) {
  5516. var result = new Matrix();
  5517. this.scaleToRef(scale, result);
  5518. return result;
  5519. };
  5520. /**
  5521. * Scale the current matrix values by a factor to a given result matrix
  5522. * @param scale defines the scale factor
  5523. * @param result defines the matrix to store the result
  5524. * @returns the current matrix
  5525. */
  5526. Matrix.prototype.scaleToRef = function (scale, result) {
  5527. for (var index = 0; index < 16; index++) {
  5528. result.m[index] = this.m[index] * scale;
  5529. }
  5530. result._markAsUpdated();
  5531. return this;
  5532. };
  5533. /**
  5534. * Scale the current matrix values by a factor and add the result to a given matrix
  5535. * @param scale defines the scale factor
  5536. * @param result defines the Matrix to store the result
  5537. * @returns the current matrix
  5538. */
  5539. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5540. for (var index = 0; index < 16; index++) {
  5541. result.m[index] += this.m[index] * scale;
  5542. }
  5543. result._markAsUpdated();
  5544. return this;
  5545. };
  5546. /**
  5547. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5548. * @param ref matrix to store the result
  5549. */
  5550. Matrix.prototype.toNormalMatrix = function (ref) {
  5551. this.invertToRef(ref);
  5552. ref.transpose();
  5553. var m = ref.m;
  5554. 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);
  5555. };
  5556. /**
  5557. * Gets only rotation part of the current matrix
  5558. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5559. */
  5560. Matrix.prototype.getRotationMatrix = function () {
  5561. var result = Matrix.Identity();
  5562. this.getRotationMatrixToRef(result);
  5563. return result;
  5564. };
  5565. /**
  5566. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5567. * @param result defines the target matrix to store data to
  5568. * @returns the current matrix
  5569. */
  5570. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5571. var m = this.m;
  5572. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5573. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5574. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5575. if (this.determinant() <= 0) {
  5576. sy *= -1;
  5577. }
  5578. if (sx === 0 || sy === 0 || sz === 0) {
  5579. Matrix.IdentityToRef(result);
  5580. }
  5581. else {
  5582. 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);
  5583. }
  5584. return this;
  5585. };
  5586. // Statics
  5587. /**
  5588. * Creates a matrix from an array
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @returns a new Matrix set from the starting index of the given array
  5592. */
  5593. Matrix.FromArray = function (array, offset) {
  5594. var result = new Matrix();
  5595. if (!offset) {
  5596. offset = 0;
  5597. }
  5598. Matrix.FromArrayToRef(array, offset, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Copy the content of an array into a given matrix
  5603. * @param array defines the source array
  5604. * @param offset defines an offset in the source array
  5605. * @param result defines the target matrix
  5606. */
  5607. Matrix.FromArrayToRef = function (array, offset, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = array[index + offset];
  5610. }
  5611. result._markAsUpdated();
  5612. };
  5613. /**
  5614. * Stores an array into a matrix after having multiplied each component by a given factor
  5615. * @param array defines the source array
  5616. * @param offset defines the offset in the source array
  5617. * @param scale defines the scaling factor
  5618. * @param result defines the target matrix
  5619. */
  5620. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = array[index + offset] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Stores a list of values (16) inside a given matrix
  5628. * @param initialM11 defines 1st value of 1st row
  5629. * @param initialM12 defines 2nd value of 1st row
  5630. * @param initialM13 defines 3rd value of 1st row
  5631. * @param initialM14 defines 4th value of 1st row
  5632. * @param initialM21 defines 1st value of 2nd row
  5633. * @param initialM22 defines 2nd value of 2nd row
  5634. * @param initialM23 defines 3rd value of 2nd row
  5635. * @param initialM24 defines 4th value of 2nd row
  5636. * @param initialM31 defines 1st value of 3rd row
  5637. * @param initialM32 defines 2nd value of 3rd row
  5638. * @param initialM33 defines 3rd value of 3rd row
  5639. * @param initialM34 defines 4th value of 3rd row
  5640. * @param initialM41 defines 1st value of 4th row
  5641. * @param initialM42 defines 2nd value of 4th row
  5642. * @param initialM43 defines 3rd value of 4th row
  5643. * @param initialM44 defines 4th value of 4th row
  5644. * @param result defines the target matrix
  5645. */
  5646. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5647. result.m[0] = initialM11;
  5648. result.m[1] = initialM12;
  5649. result.m[2] = initialM13;
  5650. result.m[3] = initialM14;
  5651. result.m[4] = initialM21;
  5652. result.m[5] = initialM22;
  5653. result.m[6] = initialM23;
  5654. result.m[7] = initialM24;
  5655. result.m[8] = initialM31;
  5656. result.m[9] = initialM32;
  5657. result.m[10] = initialM33;
  5658. result.m[11] = initialM34;
  5659. result.m[12] = initialM41;
  5660. result.m[13] = initialM42;
  5661. result.m[14] = initialM43;
  5662. result.m[15] = initialM44;
  5663. result._markAsUpdated();
  5664. };
  5665. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5666. /**
  5667. * Gets an identity matrix that must not be updated
  5668. */
  5669. get: function () {
  5670. return Matrix._identityReadOnly;
  5671. },
  5672. enumerable: true,
  5673. configurable: true
  5674. });
  5675. /**
  5676. * Creates new matrix from a list of values (16)
  5677. * @param initialM11 defines 1st value of 1st row
  5678. * @param initialM12 defines 2nd value of 1st row
  5679. * @param initialM13 defines 3rd value of 1st row
  5680. * @param initialM14 defines 4th value of 1st row
  5681. * @param initialM21 defines 1st value of 2nd row
  5682. * @param initialM22 defines 2nd value of 2nd row
  5683. * @param initialM23 defines 3rd value of 2nd row
  5684. * @param initialM24 defines 4th value of 2nd row
  5685. * @param initialM31 defines 1st value of 3rd row
  5686. * @param initialM32 defines 2nd value of 3rd row
  5687. * @param initialM33 defines 3rd value of 3rd row
  5688. * @param initialM34 defines 4th value of 3rd row
  5689. * @param initialM41 defines 1st value of 4th row
  5690. * @param initialM42 defines 2nd value of 4th row
  5691. * @param initialM43 defines 3rd value of 4th row
  5692. * @param initialM44 defines 4th value of 4th row
  5693. * @returns the new matrix
  5694. */
  5695. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5696. var result = new Matrix();
  5697. result.m[0] = initialM11;
  5698. result.m[1] = initialM12;
  5699. result.m[2] = initialM13;
  5700. result.m[3] = initialM14;
  5701. result.m[4] = initialM21;
  5702. result.m[5] = initialM22;
  5703. result.m[6] = initialM23;
  5704. result.m[7] = initialM24;
  5705. result.m[8] = initialM31;
  5706. result.m[9] = initialM32;
  5707. result.m[10] = initialM33;
  5708. result.m[11] = initialM34;
  5709. result.m[12] = initialM41;
  5710. result.m[13] = initialM42;
  5711. result.m[14] = initialM43;
  5712. result.m[15] = initialM44;
  5713. return result;
  5714. };
  5715. /**
  5716. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5717. * @param scale defines the scale vector3
  5718. * @param rotation defines the rotation quaternion
  5719. * @param translation defines the translation vector3
  5720. * @returns a new matrix
  5721. */
  5722. Matrix.Compose = function (scale, rotation, translation) {
  5723. var result = Matrix.Identity();
  5724. Matrix.ComposeToRef(scale, rotation, translation, result);
  5725. return result;
  5726. };
  5727. /**
  5728. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5729. * @param scale defines the scale vector3
  5730. * @param rotation defines the rotation quaternion
  5731. * @param translation defines the translation vector3
  5732. * @param result defines the target matrix
  5733. */
  5734. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5735. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5736. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5737. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5738. result.setTranslation(translation);
  5739. };
  5740. /**
  5741. * Creates a new identity matrix
  5742. * @returns a new identity matrix
  5743. */
  5744. Matrix.Identity = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new identity matrix and stores the result in a given matrix
  5749. * @param result defines the target matrix
  5750. */
  5751. Matrix.IdentityToRef = function (result) {
  5752. 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);
  5753. };
  5754. /**
  5755. * Creates a new zero matrix
  5756. * @returns a new zero matrix
  5757. */
  5758. Matrix.Zero = function () {
  5759. 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);
  5760. };
  5761. /**
  5762. * Creates a new rotation matrix for "angle" radians around the X axis
  5763. * @param angle defines the angle (in radians) to use
  5764. * @return the new matrix
  5765. */
  5766. Matrix.RotationX = function (angle) {
  5767. var result = new Matrix();
  5768. Matrix.RotationXToRef(angle, result);
  5769. return result;
  5770. };
  5771. /**
  5772. * Creates a new matrix as the invert of a given matrix
  5773. * @param source defines the source matrix
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.Invert = function (source) {
  5777. var result = new Matrix();
  5778. source.invertToRef(result);
  5779. return result;
  5780. };
  5781. /**
  5782. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5783. * @param angle defines the angle (in radians) to use
  5784. * @param result defines the target matrix
  5785. */
  5786. Matrix.RotationXToRef = function (angle, result) {
  5787. var s = Math.sin(angle);
  5788. var c = Math.cos(angle);
  5789. result.m[0] = 1.0;
  5790. result.m[15] = 1.0;
  5791. result.m[5] = c;
  5792. result.m[10] = c;
  5793. result.m[9] = -s;
  5794. result.m[6] = s;
  5795. result.m[1] = 0.0;
  5796. result.m[2] = 0.0;
  5797. result.m[3] = 0.0;
  5798. result.m[4] = 0.0;
  5799. result.m[7] = 0.0;
  5800. result.m[8] = 0.0;
  5801. result.m[11] = 0.0;
  5802. result.m[12] = 0.0;
  5803. result.m[13] = 0.0;
  5804. result.m[14] = 0.0;
  5805. result._markAsUpdated();
  5806. };
  5807. /**
  5808. * Creates a new rotation matrix for "angle" radians around the Y axis
  5809. * @param angle defines the angle (in radians) to use
  5810. * @return the new matrix
  5811. */
  5812. Matrix.RotationY = function (angle) {
  5813. var result = new Matrix();
  5814. Matrix.RotationYToRef(angle, result);
  5815. return result;
  5816. };
  5817. /**
  5818. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5819. * @param angle defines the angle (in radians) to use
  5820. * @param result defines the target matrix
  5821. */
  5822. Matrix.RotationYToRef = function (angle, result) {
  5823. var s = Math.sin(angle);
  5824. var c = Math.cos(angle);
  5825. result.m[5] = 1.0;
  5826. result.m[15] = 1.0;
  5827. result.m[0] = c;
  5828. result.m[2] = -s;
  5829. result.m[8] = s;
  5830. result.m[10] = c;
  5831. result.m[1] = 0.0;
  5832. result.m[3] = 0.0;
  5833. result.m[4] = 0.0;
  5834. result.m[6] = 0.0;
  5835. result.m[7] = 0.0;
  5836. result.m[9] = 0.0;
  5837. result.m[11] = 0.0;
  5838. result.m[12] = 0.0;
  5839. result.m[13] = 0.0;
  5840. result.m[14] = 0.0;
  5841. result._markAsUpdated();
  5842. };
  5843. /**
  5844. * Creates a new rotation matrix for "angle" radians around the Z axis
  5845. * @param angle defines the angle (in radians) to use
  5846. * @return the new matrix
  5847. */
  5848. Matrix.RotationZ = function (angle) {
  5849. var result = new Matrix();
  5850. Matrix.RotationZToRef(angle, result);
  5851. return result;
  5852. };
  5853. /**
  5854. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5855. * @param angle defines the angle (in radians) to use
  5856. * @param result defines the target matrix
  5857. */
  5858. Matrix.RotationZToRef = function (angle, result) {
  5859. var s = Math.sin(angle);
  5860. var c = Math.cos(angle);
  5861. result.m[10] = 1.0;
  5862. result.m[15] = 1.0;
  5863. result.m[0] = c;
  5864. result.m[1] = s;
  5865. result.m[4] = -s;
  5866. result.m[5] = c;
  5867. result.m[2] = 0.0;
  5868. result.m[3] = 0.0;
  5869. result.m[6] = 0.0;
  5870. result.m[7] = 0.0;
  5871. result.m[8] = 0.0;
  5872. result.m[9] = 0.0;
  5873. result.m[11] = 0.0;
  5874. result.m[12] = 0.0;
  5875. result.m[13] = 0.0;
  5876. result.m[14] = 0.0;
  5877. result._markAsUpdated();
  5878. };
  5879. /**
  5880. * Creates a new rotation matrix for "angle" radians around the given axis
  5881. * @param axis defines the axis to use
  5882. * @param angle defines the angle (in radians) to use
  5883. * @return the new matrix
  5884. */
  5885. Matrix.RotationAxis = function (axis, angle) {
  5886. var result = Matrix.Zero();
  5887. Matrix.RotationAxisToRef(axis, angle, result);
  5888. return result;
  5889. };
  5890. /**
  5891. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5892. * @param axis defines the axis to use
  5893. * @param angle defines the angle (in radians) to use
  5894. * @param result defines the target matrix
  5895. */
  5896. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5897. var s = Math.sin(-angle);
  5898. var c = Math.cos(-angle);
  5899. var c1 = 1 - c;
  5900. axis.normalize();
  5901. result.m[0] = (axis.x * axis.x) * c1 + c;
  5902. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5903. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5904. result.m[3] = 0.0;
  5905. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5906. result.m[5] = (axis.y * axis.y) * c1 + c;
  5907. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5908. result.m[7] = 0.0;
  5909. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5910. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5911. result.m[10] = (axis.z * axis.z) * c1 + c;
  5912. result.m[11] = 0.0;
  5913. result.m[15] = 1.0;
  5914. result._markAsUpdated();
  5915. };
  5916. /**
  5917. * Creates a rotation matrix
  5918. * @param yaw defines the yaw angle in radians (Y axis)
  5919. * @param pitch defines the pitch angle in radians (X axis)
  5920. * @param roll defines the roll angle in radians (X axis)
  5921. * @returns the new rotation matrix
  5922. */
  5923. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5924. var result = new Matrix();
  5925. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5926. return result;
  5927. };
  5928. /**
  5929. * Creates a rotation matrix and stores it in a given matrix
  5930. * @param yaw defines the yaw angle in radians (Y axis)
  5931. * @param pitch defines the pitch angle in radians (X axis)
  5932. * @param roll defines the roll angle in radians (X axis)
  5933. * @param result defines the target matrix
  5934. */
  5935. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5936. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5937. this._tempQuaternion.toRotationMatrix(result);
  5938. };
  5939. /**
  5940. * Creates a scaling matrix
  5941. * @param x defines the scale factor on X axis
  5942. * @param y defines the scale factor on Y axis
  5943. * @param z defines the scale factor on Z axis
  5944. * @returns the new matrix
  5945. */
  5946. Matrix.Scaling = function (x, y, z) {
  5947. var result = Matrix.Zero();
  5948. Matrix.ScalingToRef(x, y, z, result);
  5949. return result;
  5950. };
  5951. /**
  5952. * Creates a scaling matrix and stores it in a given matrix
  5953. * @param x defines the scale factor on X axis
  5954. * @param y defines the scale factor on Y axis
  5955. * @param z defines the scale factor on Z axis
  5956. * @param result defines the target matrix
  5957. */
  5958. Matrix.ScalingToRef = function (x, y, z, result) {
  5959. result.m[0] = x;
  5960. result.m[1] = 0.0;
  5961. result.m[2] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[4] = 0.0;
  5964. result.m[5] = y;
  5965. result.m[6] = 0.0;
  5966. result.m[7] = 0.0;
  5967. result.m[8] = 0.0;
  5968. result.m[9] = 0.0;
  5969. result.m[10] = z;
  5970. result.m[11] = 0.0;
  5971. result.m[12] = 0.0;
  5972. result.m[13] = 0.0;
  5973. result.m[14] = 0.0;
  5974. result.m[15] = 1.0;
  5975. result._markAsUpdated();
  5976. };
  5977. /**
  5978. * Creates a translation matrix
  5979. * @param x defines the translation on X axis
  5980. * @param y defines the translation on Y axis
  5981. * @param z defines the translationon Z axis
  5982. * @returns the new matrix
  5983. */
  5984. Matrix.Translation = function (x, y, z) {
  5985. var result = Matrix.Identity();
  5986. Matrix.TranslationToRef(x, y, z, result);
  5987. return result;
  5988. };
  5989. /**
  5990. * Creates a translation matrix and stores it in a given matrix
  5991. * @param x defines the translation on X axis
  5992. * @param y defines the translation on Y axis
  5993. * @param z defines the translationon Z axis
  5994. * @param result defines the target matrix
  5995. */
  5996. Matrix.TranslationToRef = function (x, y, z, result) {
  5997. 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);
  5998. };
  5999. /**
  6000. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6001. * @param startValue defines the start value
  6002. * @param endValue defines the end value
  6003. * @param gradient defines the gradient factor
  6004. * @returns the new matrix
  6005. */
  6006. Matrix.Lerp = function (startValue, endValue, gradient) {
  6007. var result = Matrix.Zero();
  6008. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6009. return result;
  6010. };
  6011. /**
  6012. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6013. * @param startValue defines the start value
  6014. * @param endValue defines the end value
  6015. * @param gradient defines the gradient factor
  6016. * @param result defines the Matrix object where to store data
  6017. */
  6018. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6019. for (var index = 0; index < 16; index++) {
  6020. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6021. }
  6022. result._markAsUpdated();
  6023. };
  6024. /**
  6025. * Builds a new matrix whose values are computed by:
  6026. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6027. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6028. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6029. * @param startValue defines the first matrix
  6030. * @param endValue defines the second matrix
  6031. * @param gradient defines the gradient between the two matrices
  6032. * @returns the new matrix
  6033. */
  6034. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6035. var result = Matrix.Zero();
  6036. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6037. return result;
  6038. };
  6039. /**
  6040. * Update a matrix to values which are computed by:
  6041. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6042. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6043. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6044. * @param startValue defines the first matrix
  6045. * @param endValue defines the second matrix
  6046. * @param gradient defines the gradient between the two matrices
  6047. * @param result defines the target matrix
  6048. */
  6049. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6050. var startScale = MathTmp.Vector3[0];
  6051. var startRotation = MathTmp.Quaternion[0];
  6052. var startTranslation = MathTmp.Vector3[1];
  6053. startValue.decompose(startScale, startRotation, startTranslation);
  6054. var endScale = MathTmp.Vector3[2];
  6055. var endRotation = MathTmp.Quaternion[1];
  6056. var endTranslation = MathTmp.Vector3[3];
  6057. endValue.decompose(endScale, endRotation, endTranslation);
  6058. var resultScale = MathTmp.Vector3[4];
  6059. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6060. var resultRotation = MathTmp.Quaternion[2];
  6061. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6062. var resultTranslation = MathTmp.Vector3[5];
  6063. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6064. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6065. };
  6066. /**
  6067. * 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"
  6068. * This function works in left handed mode
  6069. * @param eye defines the final position of the entity
  6070. * @param target defines where the entity should look at
  6071. * @param up defines the up vector for the entity
  6072. * @returns the new matrix
  6073. */
  6074. Matrix.LookAtLH = function (eye, target, up) {
  6075. var result = Matrix.Zero();
  6076. Matrix.LookAtLHToRef(eye, target, up, result);
  6077. return result;
  6078. };
  6079. /**
  6080. * 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".
  6081. * This function works in left handed mode
  6082. * @param eye defines the final position of the entity
  6083. * @param target defines where the entity should look at
  6084. * @param up defines the up vector for the entity
  6085. * @param result defines the target matrix
  6086. */
  6087. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6088. // Z axis
  6089. target.subtractToRef(eye, this._zAxis);
  6090. this._zAxis.normalize();
  6091. // X axis
  6092. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6093. if (this._xAxis.lengthSquared() === 0) {
  6094. this._xAxis.x = 1.0;
  6095. }
  6096. else {
  6097. this._xAxis.normalize();
  6098. }
  6099. // Y axis
  6100. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6101. this._yAxis.normalize();
  6102. // Eye angles
  6103. var ex = -Vector3.Dot(this._xAxis, eye);
  6104. var ey = -Vector3.Dot(this._yAxis, eye);
  6105. var ez = -Vector3.Dot(this._zAxis, eye);
  6106. 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);
  6107. };
  6108. /**
  6109. * 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"
  6110. * This function works in right handed mode
  6111. * @param eye defines the final position of the entity
  6112. * @param target defines where the entity should look at
  6113. * @param up defines the up vector for the entity
  6114. * @returns the new matrix
  6115. */
  6116. Matrix.LookAtRH = function (eye, target, up) {
  6117. var result = Matrix.Zero();
  6118. Matrix.LookAtRHToRef(eye, target, up, result);
  6119. return result;
  6120. };
  6121. /**
  6122. * 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".
  6123. * This function works in right handed mode
  6124. * @param eye defines the final position of the entity
  6125. * @param target defines where the entity should look at
  6126. * @param up defines the up vector for the entity
  6127. * @param result defines the target matrix
  6128. */
  6129. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6130. // Z axis
  6131. eye.subtractToRef(target, this._zAxis);
  6132. this._zAxis.normalize();
  6133. // X axis
  6134. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6135. if (this._xAxis.lengthSquared() === 0) {
  6136. this._xAxis.x = 1.0;
  6137. }
  6138. else {
  6139. this._xAxis.normalize();
  6140. }
  6141. // Y axis
  6142. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6143. this._yAxis.normalize();
  6144. // Eye angles
  6145. var ex = -Vector3.Dot(this._xAxis, eye);
  6146. var ey = -Vector3.Dot(this._yAxis, eye);
  6147. var ez = -Vector3.Dot(this._zAxis, eye);
  6148. 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);
  6149. };
  6150. /**
  6151. * Create a left-handed orthographic projection matrix
  6152. * @param width defines the viewport width
  6153. * @param height defines the viewport height
  6154. * @param znear defines the near clip plane
  6155. * @param zfar defines the far clip plane
  6156. * @returns a new matrix as a left-handed orthographic projection matrix
  6157. */
  6158. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6159. var matrix = Matrix.Zero();
  6160. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6161. return matrix;
  6162. };
  6163. /**
  6164. * Store a left-handed orthographic projection to a given matrix
  6165. * @param width defines the viewport width
  6166. * @param height defines the viewport height
  6167. * @param znear defines the near clip plane
  6168. * @param zfar defines the far clip plane
  6169. * @param result defines the target matrix
  6170. */
  6171. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6172. var n = znear;
  6173. var f = zfar;
  6174. var a = 2.0 / width;
  6175. var b = 2.0 / height;
  6176. var c = 2.0 / (f - n);
  6177. var d = -(f + n) / (f - n);
  6178. 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);
  6179. };
  6180. /**
  6181. * Create a left-handed orthographic projection matrix
  6182. * @param left defines the viewport left coordinate
  6183. * @param right defines the viewport right coordinate
  6184. * @param bottom defines the viewport bottom coordinate
  6185. * @param top defines the viewport top coordinate
  6186. * @param znear defines the near clip plane
  6187. * @param zfar defines the far clip plane
  6188. * @returns a new matrix as a left-handed orthographic projection matrix
  6189. */
  6190. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6191. var matrix = Matrix.Zero();
  6192. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6193. return matrix;
  6194. };
  6195. /**
  6196. * Stores a left-handed orthographic projection into a given matrix
  6197. * @param left defines the viewport left coordinate
  6198. * @param right defines the viewport right coordinate
  6199. * @param bottom defines the viewport bottom coordinate
  6200. * @param top defines the viewport top coordinate
  6201. * @param znear defines the near clip plane
  6202. * @param zfar defines the far clip plane
  6203. * @param result defines the target matrix
  6204. */
  6205. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6206. var n = znear;
  6207. var f = zfar;
  6208. var a = 2.0 / (right - left);
  6209. var b = 2.0 / (top - bottom);
  6210. var c = 2.0 / (f - n);
  6211. var d = -(f + n) / (f - n);
  6212. var i0 = (left + right) / (left - right);
  6213. var i1 = (top + bottom) / (bottom - top);
  6214. 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);
  6215. };
  6216. /**
  6217. * Creates a right-handed orthographic projection matrix
  6218. * @param left defines the viewport left coordinate
  6219. * @param right defines the viewport right coordinate
  6220. * @param bottom defines the viewport bottom coordinate
  6221. * @param top defines the viewport top coordinate
  6222. * @param znear defines the near clip plane
  6223. * @param zfar defines the far clip plane
  6224. * @returns a new matrix as a right-handed orthographic projection matrix
  6225. */
  6226. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6227. var matrix = Matrix.Zero();
  6228. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6229. return matrix;
  6230. };
  6231. /**
  6232. * Stores a right-handed orthographic projection into a given matrix
  6233. * @param left defines the viewport left coordinate
  6234. * @param right defines the viewport right coordinate
  6235. * @param bottom defines the viewport bottom coordinate
  6236. * @param top defines the viewport top coordinate
  6237. * @param znear defines the near clip plane
  6238. * @param zfar defines the far clip plane
  6239. * @param result defines the target matrix
  6240. */
  6241. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6242. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6243. result.m[10] *= -1.0;
  6244. };
  6245. /**
  6246. * Creates a left-handed perspective projection matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. var n = znear;
  6256. var f = zfar;
  6257. var a = 2.0 * n / width;
  6258. var b = 2.0 * n / height;
  6259. var c = (f + n) / (f - n);
  6260. var d = -2.0 * f * n / (f - n);
  6261. 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);
  6262. return matrix;
  6263. };
  6264. /**
  6265. * Creates a left-handed perspective projection matrix
  6266. * @param fov defines the horizontal field of view
  6267. * @param aspect defines the aspect ratio
  6268. * @param znear defines the near clip plane
  6269. * @param zfar defines the far clip plane
  6270. * @returns a new matrix as a left-handed perspective projection matrix
  6271. */
  6272. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6273. var matrix = Matrix.Zero();
  6274. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6275. return matrix;
  6276. };
  6277. /**
  6278. * Stores a left-handed perspective projection into a given matrix
  6279. * @param fov defines the horizontal field of view
  6280. * @param aspect defines the aspect ratio
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @param result defines the target matrix
  6284. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6285. */
  6286. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6287. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6288. var n = znear;
  6289. var f = zfar;
  6290. var t = 1.0 / (Math.tan(fov * 0.5));
  6291. var a = isVerticalFovFixed ? (t / aspect) : t;
  6292. var b = isVerticalFovFixed ? t : (t * aspect);
  6293. var c = (f + n) / (f - n);
  6294. var d = -2.0 * f * n / (f - n);
  6295. 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);
  6296. };
  6297. /**
  6298. * Creates a right-handed perspective projection matrix
  6299. * @param fov defines the horizontal field of view
  6300. * @param aspect defines the aspect ratio
  6301. * @param znear defines the near clip plane
  6302. * @param zfar defines the far clip plane
  6303. * @returns a new matrix as a right-handed perspective projection matrix
  6304. */
  6305. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6306. var matrix = Matrix.Zero();
  6307. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6308. return matrix;
  6309. };
  6310. /**
  6311. * Stores a right-handed perspective projection into a given matrix
  6312. * @param fov defines the horizontal field of view
  6313. * @param aspect defines the aspect ratio
  6314. * @param znear defines the near clip plane
  6315. * @param zfar defines the far clip plane
  6316. * @param result defines the target matrix
  6317. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6318. */
  6319. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6320. //alternatively this could be expressed as:
  6321. // m = PerspectiveFovLHToRef
  6322. // m[10] *= -1.0;
  6323. // m[11] *= -1.0;
  6324. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6325. var n = znear;
  6326. var f = zfar;
  6327. var t = 1.0 / (Math.tan(fov * 0.5));
  6328. var a = isVerticalFovFixed ? (t / aspect) : t;
  6329. var b = isVerticalFovFixed ? t : (t * aspect);
  6330. var c = -(f + n) / (f - n);
  6331. var d = -2 * f * n / (f - n);
  6332. 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);
  6333. };
  6334. /**
  6335. * Stores a perspective projection for WebVR info a given matrix
  6336. * @param fov defines the field of view
  6337. * @param znear defines the near clip plane
  6338. * @param zfar defines the far clip plane
  6339. * @param result defines the target matrix
  6340. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6341. */
  6342. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6343. if (rightHanded === void 0) { rightHanded = false; }
  6344. var rightHandedFactor = rightHanded ? -1 : 1;
  6345. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6346. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6347. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6348. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6349. var xScale = 2.0 / (leftTan + rightTan);
  6350. var yScale = 2.0 / (upTan + downTan);
  6351. result.m[0] = xScale;
  6352. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6353. result.m[5] = yScale;
  6354. result.m[6] = result.m[7] = 0.0;
  6355. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6356. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6357. result.m[10] = -zfar / (znear - zfar);
  6358. result.m[11] = 1.0 * rightHandedFactor;
  6359. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6360. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6361. result._markAsUpdated();
  6362. };
  6363. /**
  6364. * Computes a complete transformation matrix
  6365. * @param viewport defines the viewport to use
  6366. * @param world defines the world matrix
  6367. * @param view defines the view matrix
  6368. * @param projection defines the projection matrix
  6369. * @param zmin defines the near clip plane
  6370. * @param zmax defines the far clip plane
  6371. * @returns the transformation matrix
  6372. */
  6373. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6374. var cw = viewport.width;
  6375. var ch = viewport.height;
  6376. var cx = viewport.x;
  6377. var cy = viewport.y;
  6378. 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);
  6379. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6380. };
  6381. /**
  6382. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6383. * @param matrix defines the matrix to use
  6384. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6385. */
  6386. Matrix.GetAsMatrix2x2 = function (matrix) {
  6387. return new Float32Array([
  6388. matrix.m[0], matrix.m[1],
  6389. matrix.m[4], matrix.m[5]
  6390. ]);
  6391. };
  6392. /**
  6393. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6394. * @param matrix defines the matrix to use
  6395. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6396. */
  6397. Matrix.GetAsMatrix3x3 = function (matrix) {
  6398. return new Float32Array([
  6399. matrix.m[0], matrix.m[1], matrix.m[2],
  6400. matrix.m[4], matrix.m[5], matrix.m[6],
  6401. matrix.m[8], matrix.m[9], matrix.m[10]
  6402. ]);
  6403. };
  6404. /**
  6405. * Compute the transpose of a given matrix
  6406. * @param matrix defines the matrix to transpose
  6407. * @returns the new matrix
  6408. */
  6409. Matrix.Transpose = function (matrix) {
  6410. var result = new Matrix();
  6411. Matrix.TransposeToRef(matrix, result);
  6412. return result;
  6413. };
  6414. /**
  6415. * Compute the transpose of a matrix and store it in a target matrix
  6416. * @param matrix defines the matrix to transpose
  6417. * @param result defines the target matrix
  6418. */
  6419. Matrix.TransposeToRef = function (matrix, result) {
  6420. result.m[0] = matrix.m[0];
  6421. result.m[1] = matrix.m[4];
  6422. result.m[2] = matrix.m[8];
  6423. result.m[3] = matrix.m[12];
  6424. result.m[4] = matrix.m[1];
  6425. result.m[5] = matrix.m[5];
  6426. result.m[6] = matrix.m[9];
  6427. result.m[7] = matrix.m[13];
  6428. result.m[8] = matrix.m[2];
  6429. result.m[9] = matrix.m[6];
  6430. result.m[10] = matrix.m[10];
  6431. result.m[11] = matrix.m[14];
  6432. result.m[12] = matrix.m[3];
  6433. result.m[13] = matrix.m[7];
  6434. result.m[14] = matrix.m[11];
  6435. result.m[15] = matrix.m[15];
  6436. };
  6437. /**
  6438. * Computes a reflection matrix from a plane
  6439. * @param plane defines the reflection plane
  6440. * @returns a new matrix
  6441. */
  6442. Matrix.Reflection = function (plane) {
  6443. var matrix = new Matrix();
  6444. Matrix.ReflectionToRef(plane, matrix);
  6445. return matrix;
  6446. };
  6447. /**
  6448. * Computes a reflection matrix from a plane
  6449. * @param plane defines the reflection plane
  6450. * @param result defines the target matrix
  6451. */
  6452. Matrix.ReflectionToRef = function (plane, result) {
  6453. plane.normalize();
  6454. var x = plane.normal.x;
  6455. var y = plane.normal.y;
  6456. var z = plane.normal.z;
  6457. var temp = -2 * x;
  6458. var temp2 = -2 * y;
  6459. var temp3 = -2 * z;
  6460. result.m[0] = (temp * x) + 1;
  6461. result.m[1] = temp2 * x;
  6462. result.m[2] = temp3 * x;
  6463. result.m[3] = 0.0;
  6464. result.m[4] = temp * y;
  6465. result.m[5] = (temp2 * y) + 1;
  6466. result.m[6] = temp3 * y;
  6467. result.m[7] = 0.0;
  6468. result.m[8] = temp * z;
  6469. result.m[9] = temp2 * z;
  6470. result.m[10] = (temp3 * z) + 1;
  6471. result.m[11] = 0.0;
  6472. result.m[12] = temp * plane.d;
  6473. result.m[13] = temp2 * plane.d;
  6474. result.m[14] = temp3 * plane.d;
  6475. result.m[15] = 1.0;
  6476. result._markAsUpdated();
  6477. };
  6478. /**
  6479. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6480. * @param xaxis defines the value of the 1st axis
  6481. * @param yaxis defines the value of the 2nd axis
  6482. * @param zaxis defines the value of the 3rd axis
  6483. * @param result defines the target matrix
  6484. */
  6485. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6486. result.m[0] = xaxis.x;
  6487. result.m[1] = xaxis.y;
  6488. result.m[2] = xaxis.z;
  6489. result.m[3] = 0.0;
  6490. result.m[4] = yaxis.x;
  6491. result.m[5] = yaxis.y;
  6492. result.m[6] = yaxis.z;
  6493. result.m[7] = 0.0;
  6494. result.m[8] = zaxis.x;
  6495. result.m[9] = zaxis.y;
  6496. result.m[10] = zaxis.z;
  6497. result.m[11] = 0.0;
  6498. result.m[12] = 0.0;
  6499. result.m[13] = 0.0;
  6500. result.m[14] = 0.0;
  6501. result.m[15] = 1.0;
  6502. result._markAsUpdated();
  6503. };
  6504. /**
  6505. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6506. * @param quat defines the quaternion to use
  6507. * @param result defines the target matrix
  6508. */
  6509. Matrix.FromQuaternionToRef = function (quat, result) {
  6510. var xx = quat.x * quat.x;
  6511. var yy = quat.y * quat.y;
  6512. var zz = quat.z * quat.z;
  6513. var xy = quat.x * quat.y;
  6514. var zw = quat.z * quat.w;
  6515. var zx = quat.z * quat.x;
  6516. var yw = quat.y * quat.w;
  6517. var yz = quat.y * quat.z;
  6518. var xw = quat.x * quat.w;
  6519. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6520. result.m[1] = 2.0 * (xy + zw);
  6521. result.m[2] = 2.0 * (zx - yw);
  6522. result.m[3] = 0.0;
  6523. result.m[4] = 2.0 * (xy - zw);
  6524. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6525. result.m[6] = 2.0 * (yz + xw);
  6526. result.m[7] = 0.0;
  6527. result.m[8] = 2.0 * (zx + yw);
  6528. result.m[9] = 2.0 * (yz - xw);
  6529. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6530. result.m[11] = 0.0;
  6531. result.m[12] = 0.0;
  6532. result.m[13] = 0.0;
  6533. result.m[14] = 0.0;
  6534. result.m[15] = 1.0;
  6535. result._markAsUpdated();
  6536. };
  6537. Matrix._tempQuaternion = new Quaternion();
  6538. Matrix._xAxis = Vector3.Zero();
  6539. Matrix._yAxis = Vector3.Zero();
  6540. Matrix._zAxis = Vector3.Zero();
  6541. Matrix._updateFlagSeed = 0;
  6542. Matrix._identityReadOnly = Matrix.Identity();
  6543. return Matrix;
  6544. }());
  6545. BABYLON.Matrix = Matrix;
  6546. var Plane = /** @class */ (function () {
  6547. /**
  6548. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6549. */
  6550. function Plane(a, b, c, d) {
  6551. this.normal = new Vector3(a, b, c);
  6552. this.d = d;
  6553. }
  6554. /**
  6555. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6556. */
  6557. Plane.prototype.asArray = function () {
  6558. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6559. };
  6560. // Methods
  6561. /**
  6562. * Returns a new plane copied from the current Plane.
  6563. */
  6564. Plane.prototype.clone = function () {
  6565. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6566. };
  6567. /**
  6568. * Returns the string "Plane".
  6569. */
  6570. Plane.prototype.getClassName = function () {
  6571. return "Plane";
  6572. };
  6573. /**
  6574. * Returns the Plane hash code.
  6575. */
  6576. Plane.prototype.getHashCode = function () {
  6577. var hash = this.normal.getHashCode();
  6578. hash = (hash * 397) ^ (this.d || 0);
  6579. return hash;
  6580. };
  6581. /**
  6582. * Normalize the current Plane in place.
  6583. * Returns the updated Plane.
  6584. */
  6585. Plane.prototype.normalize = function () {
  6586. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6587. var magnitude = 0.0;
  6588. if (norm !== 0) {
  6589. magnitude = 1.0 / norm;
  6590. }
  6591. this.normal.x *= magnitude;
  6592. this.normal.y *= magnitude;
  6593. this.normal.z *= magnitude;
  6594. this.d *= magnitude;
  6595. return this;
  6596. };
  6597. /**
  6598. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6599. */
  6600. Plane.prototype.transform = function (transformation) {
  6601. var transposedMatrix = Matrix.Transpose(transformation);
  6602. var x = this.normal.x;
  6603. var y = this.normal.y;
  6604. var z = this.normal.z;
  6605. var d = this.d;
  6606. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6607. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6608. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6609. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6610. return new Plane(normalX, normalY, normalZ, finalD);
  6611. };
  6612. /**
  6613. * Returns the dot product (float) of the point coordinates and the plane normal.
  6614. */
  6615. Plane.prototype.dotCoordinate = function (point) {
  6616. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6617. };
  6618. /**
  6619. * Updates the current Plane from the plane defined by the three given points.
  6620. * Returns the updated Plane.
  6621. */
  6622. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6623. var x1 = point2.x - point1.x;
  6624. var y1 = point2.y - point1.y;
  6625. var z1 = point2.z - point1.z;
  6626. var x2 = point3.x - point1.x;
  6627. var y2 = point3.y - point1.y;
  6628. var z2 = point3.z - point1.z;
  6629. var yz = (y1 * z2) - (z1 * y2);
  6630. var xz = (z1 * x2) - (x1 * z2);
  6631. var xy = (x1 * y2) - (y1 * x2);
  6632. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6633. var invPyth;
  6634. if (pyth !== 0) {
  6635. invPyth = 1.0 / pyth;
  6636. }
  6637. else {
  6638. invPyth = 0.0;
  6639. }
  6640. this.normal.x = yz * invPyth;
  6641. this.normal.y = xz * invPyth;
  6642. this.normal.z = xy * invPyth;
  6643. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6644. return this;
  6645. };
  6646. /**
  6647. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6648. */
  6649. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6650. var dot = Vector3.Dot(this.normal, direction);
  6651. return (dot <= epsilon);
  6652. };
  6653. /**
  6654. * Returns the signed distance (float) from the given point to the Plane.
  6655. */
  6656. Plane.prototype.signedDistanceTo = function (point) {
  6657. return Vector3.Dot(point, this.normal) + this.d;
  6658. };
  6659. // Statics
  6660. /**
  6661. * Returns a new Plane from the given array.
  6662. */
  6663. Plane.FromArray = function (array) {
  6664. return new Plane(array[0], array[1], array[2], array[3]);
  6665. };
  6666. /**
  6667. * Returns a new Plane defined by the three given points.
  6668. */
  6669. Plane.FromPoints = function (point1, point2, point3) {
  6670. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6671. result.copyFromPoints(point1, point2, point3);
  6672. return result;
  6673. };
  6674. /**
  6675. * Returns a new Plane the normal vector to this plane at the given origin point.
  6676. * Note : the vector "normal" is updated because normalized.
  6677. */
  6678. Plane.FromPositionAndNormal = function (origin, normal) {
  6679. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6680. normal.normalize();
  6681. result.normal = normal;
  6682. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6683. return result;
  6684. };
  6685. /**
  6686. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6687. */
  6688. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6689. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6690. return Vector3.Dot(point, normal) + d;
  6691. };
  6692. return Plane;
  6693. }());
  6694. BABYLON.Plane = Plane;
  6695. var Viewport = /** @class */ (function () {
  6696. /**
  6697. * Creates a Viewport object located at (x, y) and sized (width, height).
  6698. */
  6699. function Viewport(x, y, width, height) {
  6700. this.x = x;
  6701. this.y = y;
  6702. this.width = width;
  6703. this.height = height;
  6704. }
  6705. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6706. if (renderWidthOrEngine.getRenderWidth) {
  6707. var engine = renderWidthOrEngine;
  6708. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6709. }
  6710. var renderWidth = renderWidthOrEngine;
  6711. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6712. };
  6713. /**
  6714. * Returns a new Viewport copied from the current one.
  6715. */
  6716. Viewport.prototype.clone = function () {
  6717. return new Viewport(this.x, this.y, this.width, this.height);
  6718. };
  6719. return Viewport;
  6720. }());
  6721. BABYLON.Viewport = Viewport;
  6722. var Frustum = /** @class */ (function () {
  6723. function Frustum() {
  6724. }
  6725. /**
  6726. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6727. */
  6728. Frustum.GetPlanes = function (transform) {
  6729. var frustumPlanes = [];
  6730. for (var index = 0; index < 6; index++) {
  6731. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6732. }
  6733. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6734. return frustumPlanes;
  6735. };
  6736. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6740. frustumPlane.d = transform.m[15] + transform.m[14];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6747. frustumPlane.d = transform.m[15] - transform.m[14];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6752. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6753. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6754. frustumPlane.d = transform.m[15] + transform.m[12];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6759. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6760. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6761. frustumPlane.d = transform.m[15] - transform.m[12];
  6762. frustumPlane.normalize();
  6763. };
  6764. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6765. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6766. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6767. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6768. frustumPlane.d = transform.m[15] - transform.m[13];
  6769. frustumPlane.normalize();
  6770. };
  6771. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6772. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6773. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6774. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6775. frustumPlane.d = transform.m[15] + transform.m[13];
  6776. frustumPlane.normalize();
  6777. };
  6778. /**
  6779. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6780. */
  6781. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6782. // Near
  6783. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6784. // Far
  6785. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6786. // Left
  6787. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6788. // Right
  6789. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6790. // Top
  6791. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6792. // Bottom
  6793. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6794. };
  6795. return Frustum;
  6796. }());
  6797. BABYLON.Frustum = Frustum;
  6798. /** Defines supported spaces */
  6799. var Space;
  6800. (function (Space) {
  6801. /** Local (object) space */
  6802. Space[Space["LOCAL"] = 0] = "LOCAL";
  6803. /** World space */
  6804. Space[Space["WORLD"] = 1] = "WORLD";
  6805. /** Bone space */
  6806. Space[Space["BONE"] = 2] = "BONE";
  6807. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6808. /** Defines the 3 main axes */
  6809. var Axis = /** @class */ (function () {
  6810. function Axis() {
  6811. }
  6812. /** X axis */
  6813. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6814. /** Y axis */
  6815. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6816. /** Z axis */
  6817. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6818. return Axis;
  6819. }());
  6820. BABYLON.Axis = Axis;
  6821. ;
  6822. var BezierCurve = /** @class */ (function () {
  6823. function BezierCurve() {
  6824. }
  6825. /**
  6826. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6827. */
  6828. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6829. // Extract X (which is equal to time here)
  6830. var f0 = 1 - 3 * x2 + 3 * x1;
  6831. var f1 = 3 * x2 - 6 * x1;
  6832. var f2 = 3 * x1;
  6833. var refinedT = t;
  6834. for (var i = 0; i < 5; i++) {
  6835. var refinedT2 = refinedT * refinedT;
  6836. var refinedT3 = refinedT2 * refinedT;
  6837. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6838. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6839. refinedT -= (x - t) * slope;
  6840. refinedT = Math.min(1, Math.max(0, refinedT));
  6841. }
  6842. // Resolve cubic bezier for the given x
  6843. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6844. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6845. Math.pow(refinedT, 3);
  6846. };
  6847. return BezierCurve;
  6848. }());
  6849. BABYLON.BezierCurve = BezierCurve;
  6850. /**
  6851. * Defines potential orientation for back face culling
  6852. */
  6853. var Orientation;
  6854. (function (Orientation) {
  6855. /**
  6856. * Clockwise
  6857. */
  6858. Orientation[Orientation["CW"] = 0] = "CW";
  6859. /** Counter clockwise */
  6860. Orientation[Orientation["CCW"] = 1] = "CCW";
  6861. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6862. /**
  6863. * Defines angle representation
  6864. */
  6865. var Angle = /** @class */ (function () {
  6866. /**
  6867. * Creates an Angle object of "radians" radians (float).
  6868. */
  6869. function Angle(radians) {
  6870. this._radians = radians;
  6871. if (this._radians < 0.0)
  6872. this._radians += (2.0 * Math.PI);
  6873. }
  6874. /**
  6875. * Get value in degrees
  6876. * @returns the Angle value in degrees (float)
  6877. */
  6878. Angle.prototype.degrees = function () {
  6879. return this._radians * 180.0 / Math.PI;
  6880. };
  6881. /**
  6882. * Get value in radians
  6883. * @returns the Angle value in radians (float)
  6884. */
  6885. Angle.prototype.radians = function () {
  6886. return this._radians;
  6887. };
  6888. /**
  6889. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6890. * @param a defines first vector
  6891. * @param b defines second vector
  6892. * @returns a new Angle
  6893. */
  6894. Angle.BetweenTwoPoints = function (a, b) {
  6895. var delta = b.subtract(a);
  6896. var theta = Math.atan2(delta.y, delta.x);
  6897. return new Angle(theta);
  6898. };
  6899. /**
  6900. * Gets a new Angle object from the given float in radians
  6901. * @param radians defines the angle value in radians
  6902. * @returns a new Angle
  6903. */
  6904. Angle.FromRadians = function (radians) {
  6905. return new Angle(radians);
  6906. };
  6907. /**
  6908. * Gets a new Angle object from the given float in degrees
  6909. * @param degrees defines the angle value in degrees
  6910. * @returns a new Angle
  6911. */
  6912. Angle.FromDegrees = function (degrees) {
  6913. return new Angle(degrees * Math.PI / 180.0);
  6914. };
  6915. return Angle;
  6916. }());
  6917. BABYLON.Angle = Angle;
  6918. var Arc2 = /** @class */ (function () {
  6919. /**
  6920. * Creates an Arc object from the three given points : start, middle and end.
  6921. */
  6922. function Arc2(startPoint, midPoint, endPoint) {
  6923. this.startPoint = startPoint;
  6924. this.midPoint = midPoint;
  6925. this.endPoint = endPoint;
  6926. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6927. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6928. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6929. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6930. 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);
  6931. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6932. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6933. var a1 = this.startAngle.degrees();
  6934. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6935. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6936. // angles correction
  6937. if (a2 - a1 > +180.0)
  6938. a2 -= 360.0;
  6939. if (a2 - a1 < -180.0)
  6940. a2 += 360.0;
  6941. if (a3 - a2 > +180.0)
  6942. a3 -= 360.0;
  6943. if (a3 - a2 < -180.0)
  6944. a3 += 360.0;
  6945. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6946. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6947. }
  6948. return Arc2;
  6949. }());
  6950. BABYLON.Arc2 = Arc2;
  6951. var Path2 = /** @class */ (function () {
  6952. /**
  6953. * Creates a Path2 object from the starting 2D coordinates x and y.
  6954. */
  6955. function Path2(x, y) {
  6956. this._points = new Array();
  6957. this._length = 0.0;
  6958. this.closed = false;
  6959. this._points.push(new Vector2(x, y));
  6960. }
  6961. /**
  6962. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addLineTo = function (x, y) {
  6966. if (this.closed) {
  6967. return this;
  6968. }
  6969. var newPoint = new Vector2(x, y);
  6970. var previousPoint = this._points[this._points.length - 1];
  6971. this._points.push(newPoint);
  6972. this._length += newPoint.subtract(previousPoint).length();
  6973. return this;
  6974. };
  6975. /**
  6976. * 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.
  6977. * Returns the updated Path2.
  6978. */
  6979. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6980. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6981. if (this.closed) {
  6982. return this;
  6983. }
  6984. var startPoint = this._points[this._points.length - 1];
  6985. var midPoint = new Vector2(midX, midY);
  6986. var endPoint = new Vector2(endX, endY);
  6987. var arc = new Arc2(startPoint, midPoint, endPoint);
  6988. var increment = arc.angle.radians() / numberOfSegments;
  6989. if (arc.orientation === Orientation.CW)
  6990. increment *= -1;
  6991. var currentAngle = arc.startAngle.radians() + increment;
  6992. for (var i = 0; i < numberOfSegments; i++) {
  6993. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6994. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6995. this.addLineTo(x, y);
  6996. currentAngle += increment;
  6997. }
  6998. return this;
  6999. };
  7000. /**
  7001. * Closes the Path2.
  7002. * Returns the Path2.
  7003. */
  7004. Path2.prototype.close = function () {
  7005. this.closed = true;
  7006. return this;
  7007. };
  7008. /**
  7009. * Returns the Path2 total length (float).
  7010. */
  7011. Path2.prototype.length = function () {
  7012. var result = this._length;
  7013. if (!this.closed) {
  7014. var lastPoint = this._points[this._points.length - 1];
  7015. var firstPoint = this._points[0];
  7016. result += (firstPoint.subtract(lastPoint).length());
  7017. }
  7018. return result;
  7019. };
  7020. /**
  7021. * Returns the Path2 internal array of points.
  7022. */
  7023. Path2.prototype.getPoints = function () {
  7024. return this._points;
  7025. };
  7026. /**
  7027. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7028. */
  7029. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7030. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7031. return Vector2.Zero();
  7032. }
  7033. var lengthPosition = normalizedLengthPosition * this.length();
  7034. var previousOffset = 0;
  7035. for (var i = 0; i < this._points.length; i++) {
  7036. var j = (i + 1) % this._points.length;
  7037. var a = this._points[i];
  7038. var b = this._points[j];
  7039. var bToA = b.subtract(a);
  7040. var nextOffset = (bToA.length() + previousOffset);
  7041. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7042. var dir = bToA.normalize();
  7043. var localOffset = lengthPosition - previousOffset;
  7044. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7045. }
  7046. previousOffset = nextOffset;
  7047. }
  7048. return Vector2.Zero();
  7049. };
  7050. /**
  7051. * Returns a new Path2 starting at the coordinates (x, y).
  7052. */
  7053. Path2.StartingAt = function (x, y) {
  7054. return new Path2(x, y);
  7055. };
  7056. return Path2;
  7057. }());
  7058. BABYLON.Path2 = Path2;
  7059. var Path3D = /** @class */ (function () {
  7060. /**
  7061. * new Path3D(path, normal, raw)
  7062. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7063. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7064. * path : an array of Vector3, the curve axis of the Path3D
  7065. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7066. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7067. */
  7068. function Path3D(path, firstNormal, raw) {
  7069. if (firstNormal === void 0) { firstNormal = null; }
  7070. this.path = path;
  7071. this._curve = new Array();
  7072. this._distances = new Array();
  7073. this._tangents = new Array();
  7074. this._normals = new Array();
  7075. this._binormals = new Array();
  7076. for (var p = 0; p < path.length; p++) {
  7077. this._curve[p] = path[p].clone(); // hard copy
  7078. }
  7079. this._raw = raw || false;
  7080. this._compute(firstNormal);
  7081. }
  7082. /**
  7083. * Returns the Path3D array of successive Vector3 designing its curve.
  7084. */
  7085. Path3D.prototype.getCurve = function () {
  7086. return this._curve;
  7087. };
  7088. /**
  7089. * Returns an array populated with tangent vectors on each Path3D curve point.
  7090. */
  7091. Path3D.prototype.getTangents = function () {
  7092. return this._tangents;
  7093. };
  7094. /**
  7095. * Returns an array populated with normal vectors on each Path3D curve point.
  7096. */
  7097. Path3D.prototype.getNormals = function () {
  7098. return this._normals;
  7099. };
  7100. /**
  7101. * Returns an array populated with binormal vectors on each Path3D curve point.
  7102. */
  7103. Path3D.prototype.getBinormals = function () {
  7104. return this._binormals;
  7105. };
  7106. /**
  7107. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7108. */
  7109. Path3D.prototype.getDistances = function () {
  7110. return this._distances;
  7111. };
  7112. /**
  7113. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7114. * Returns the same object updated.
  7115. */
  7116. Path3D.prototype.update = function (path, firstNormal) {
  7117. if (firstNormal === void 0) { firstNormal = null; }
  7118. for (var p = 0; p < path.length; p++) {
  7119. this._curve[p].x = path[p].x;
  7120. this._curve[p].y = path[p].y;
  7121. this._curve[p].z = path[p].z;
  7122. }
  7123. this._compute(firstNormal);
  7124. return this;
  7125. };
  7126. // private function compute() : computes tangents, normals and binormals
  7127. Path3D.prototype._compute = function (firstNormal) {
  7128. var l = this._curve.length;
  7129. // first and last tangents
  7130. this._tangents[0] = this._getFirstNonNullVector(0);
  7131. if (!this._raw) {
  7132. this._tangents[0].normalize();
  7133. }
  7134. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7135. if (!this._raw) {
  7136. this._tangents[l - 1].normalize();
  7137. }
  7138. // normals and binormals at first point : arbitrary vector with _normalVector()
  7139. var tg0 = this._tangents[0];
  7140. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7141. this._normals[0] = pp0;
  7142. if (!this._raw) {
  7143. this._normals[0].normalize();
  7144. }
  7145. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7146. if (!this._raw) {
  7147. this._binormals[0].normalize();
  7148. }
  7149. this._distances[0] = 0.0;
  7150. // normals and binormals : next points
  7151. var prev; // previous vector (segment)
  7152. var cur; // current vector (segment)
  7153. var curTang; // current tangent
  7154. // previous normal
  7155. var prevBinor; // previous binormal
  7156. for (var i = 1; i < l; i++) {
  7157. // tangents
  7158. prev = this._getLastNonNullVector(i);
  7159. if (i < l - 1) {
  7160. cur = this._getFirstNonNullVector(i);
  7161. this._tangents[i] = prev.add(cur);
  7162. this._tangents[i].normalize();
  7163. }
  7164. this._distances[i] = this._distances[i - 1] + prev.length();
  7165. // normals and binormals
  7166. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7167. curTang = this._tangents[i];
  7168. prevBinor = this._binormals[i - 1];
  7169. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7170. if (!this._raw) {
  7171. this._normals[i].normalize();
  7172. }
  7173. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7174. if (!this._raw) {
  7175. this._binormals[i].normalize();
  7176. }
  7177. }
  7178. };
  7179. // private function getFirstNonNullVector(index)
  7180. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7181. Path3D.prototype._getFirstNonNullVector = function (index) {
  7182. var i = 1;
  7183. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7184. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7185. i++;
  7186. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7187. }
  7188. return nNVector;
  7189. };
  7190. // private function getLastNonNullVector(index)
  7191. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7192. Path3D.prototype._getLastNonNullVector = function (index) {
  7193. var i = 1;
  7194. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7195. while (nLVector.length() === 0 && index > i + 1) {
  7196. i++;
  7197. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7198. }
  7199. return nLVector;
  7200. };
  7201. // private function normalVector(v0, vt, va) :
  7202. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7203. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7204. Path3D.prototype._normalVector = function (v0, vt, va) {
  7205. var normal0;
  7206. var tgl = vt.length();
  7207. if (tgl === 0.0) {
  7208. tgl = 1.0;
  7209. }
  7210. if (va === undefined || va === null) {
  7211. var point;
  7212. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7213. point = new Vector3(0.0, -1.0, 0.0);
  7214. }
  7215. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7216. point = new Vector3(1.0, 0.0, 0.0);
  7217. }
  7218. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7219. point = new Vector3(0.0, 0.0, 1.0);
  7220. }
  7221. else {
  7222. point = Vector3.Zero();
  7223. }
  7224. normal0 = Vector3.Cross(vt, point);
  7225. }
  7226. else {
  7227. normal0 = Vector3.Cross(vt, va);
  7228. Vector3.CrossToRef(normal0, vt, normal0);
  7229. }
  7230. normal0.normalize();
  7231. return normal0;
  7232. };
  7233. return Path3D;
  7234. }());
  7235. BABYLON.Path3D = Path3D;
  7236. var Curve3 = /** @class */ (function () {
  7237. /**
  7238. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7239. * A Curve3 is designed from a series of successive Vector3.
  7240. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7241. */
  7242. function Curve3(points) {
  7243. this._length = 0.0;
  7244. this._points = points;
  7245. this._length = this._computeLength(points);
  7246. }
  7247. /**
  7248. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7249. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7250. * @param v1 (Vector3) the control point
  7251. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7252. * @param nbPoints (integer) the wanted number of points in the curve
  7253. */
  7254. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7255. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7256. var bez = new Array();
  7257. var equation = function (t, val0, val1, val2) {
  7258. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7259. return res;
  7260. };
  7261. for (var i = 0; i <= nbPoints; i++) {
  7262. 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)));
  7263. }
  7264. return new Curve3(bez);
  7265. };
  7266. /**
  7267. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7268. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7269. * @param v1 (Vector3) the first control point
  7270. * @param v2 (Vector3) the second control point
  7271. * @param v3 (Vector3) the end point of the Cubic Bezier
  7272. * @param nbPoints (integer) the wanted number of points in the curve
  7273. */
  7274. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7275. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7276. var bez = new Array();
  7277. var equation = function (t, val0, val1, val2, val3) {
  7278. 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;
  7279. return res;
  7280. };
  7281. for (var i = 0; i <= nbPoints; i++) {
  7282. 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)));
  7283. }
  7284. return new Curve3(bez);
  7285. };
  7286. /**
  7287. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7288. * @param p1 (Vector3) the origin point of the Hermite Spline
  7289. * @param t1 (Vector3) the tangent vector at the origin point
  7290. * @param p2 (Vector3) the end point of the Hermite Spline
  7291. * @param t2 (Vector3) the tangent vector at the end point
  7292. * @param nbPoints (integer) the wanted number of points in the curve
  7293. */
  7294. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7295. var hermite = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. for (var i = 0; i <= nbPoints; i++) {
  7298. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7299. }
  7300. return new Curve3(hermite);
  7301. };
  7302. /**
  7303. * Returns a Curve3 object along a CatmullRom Spline curve :
  7304. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7305. * @param nbPoints (integer) the wanted number of points between each curve control points
  7306. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7307. */
  7308. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7309. var catmullRom = new Array();
  7310. var step = 1.0 / nbPoints;
  7311. var amount = 0.0;
  7312. if (closed) {
  7313. var pointsCount = points.length;
  7314. for (var i = 0; i < pointsCount; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. catmullRom.push(catmullRom[0]);
  7322. }
  7323. else {
  7324. var totalPoints = new Array();
  7325. totalPoints.push(points[0].clone());
  7326. Array.prototype.push.apply(totalPoints, points);
  7327. totalPoints.push(points[points.length - 1].clone());
  7328. for (var i = 0; i < totalPoints.length - 3; i++) {
  7329. amount = 0;
  7330. for (var c = 0; c < nbPoints; c++) {
  7331. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7332. amount += step;
  7333. }
  7334. }
  7335. i--;
  7336. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7337. }
  7338. return new Curve3(catmullRom);
  7339. };
  7340. /**
  7341. * Returns the Curve3 stored array of successive Vector3
  7342. */
  7343. Curve3.prototype.getPoints = function () {
  7344. return this._points;
  7345. };
  7346. /**
  7347. * Returns the computed length (float) of the curve.
  7348. */
  7349. Curve3.prototype.length = function () {
  7350. return this._length;
  7351. };
  7352. /**
  7353. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7354. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7355. * curveA and curveB keep unchanged.
  7356. */
  7357. Curve3.prototype.continue = function (curve) {
  7358. var lastPoint = this._points[this._points.length - 1];
  7359. var continuedPoints = this._points.slice();
  7360. var curvePoints = curve.getPoints();
  7361. for (var i = 1; i < curvePoints.length; i++) {
  7362. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7363. }
  7364. var continuedCurve = new Curve3(continuedPoints);
  7365. return continuedCurve;
  7366. };
  7367. Curve3.prototype._computeLength = function (path) {
  7368. var l = 0;
  7369. for (var i = 1; i < path.length; i++) {
  7370. l += (path[i].subtract(path[i - 1])).length();
  7371. }
  7372. return l;
  7373. };
  7374. return Curve3;
  7375. }());
  7376. BABYLON.Curve3 = Curve3;
  7377. // Vertex formats
  7378. var PositionNormalVertex = /** @class */ (function () {
  7379. function PositionNormalVertex(position, normal) {
  7380. if (position === void 0) { position = Vector3.Zero(); }
  7381. if (normal === void 0) { normal = Vector3.Up(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. }
  7385. PositionNormalVertex.prototype.clone = function () {
  7386. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7387. };
  7388. return PositionNormalVertex;
  7389. }());
  7390. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7391. var PositionNormalTextureVertex = /** @class */ (function () {
  7392. function PositionNormalTextureVertex(position, normal, uv) {
  7393. if (position === void 0) { position = Vector3.Zero(); }
  7394. if (normal === void 0) { normal = Vector3.Up(); }
  7395. if (uv === void 0) { uv = Vector2.Zero(); }
  7396. this.position = position;
  7397. this.normal = normal;
  7398. this.uv = uv;
  7399. }
  7400. PositionNormalTextureVertex.prototype.clone = function () {
  7401. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7402. };
  7403. return PositionNormalTextureVertex;
  7404. }());
  7405. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7406. // Temporary pre-allocated objects for engine internal use
  7407. // usage in any internal function :
  7408. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7409. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7410. var Tmp = /** @class */ (function () {
  7411. function Tmp() {
  7412. }
  7413. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7414. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7415. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7416. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7417. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7418. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7419. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7420. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7421. Matrix.Zero(), Matrix.Zero(),
  7422. Matrix.Zero(), Matrix.Zero(),
  7423. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7424. return Tmp;
  7425. }());
  7426. BABYLON.Tmp = Tmp;
  7427. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7428. var MathTmp = /** @class */ (function () {
  7429. function MathTmp() {
  7430. }
  7431. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7432. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7433. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7434. return MathTmp;
  7435. }());
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.math.js.map
  7438. var BABYLON;
  7439. (function (BABYLON) {
  7440. var Scalar = /** @class */ (function () {
  7441. function Scalar() {
  7442. }
  7443. /**
  7444. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7445. */
  7446. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7447. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7448. var num = a - b;
  7449. return -epsilon <= num && num <= epsilon;
  7450. };
  7451. /**
  7452. * Returns a string : the upper case translation of the number i to hexadecimal.
  7453. */
  7454. Scalar.ToHex = function (i) {
  7455. var str = i.toString(16);
  7456. if (i <= 15) {
  7457. return ("0" + str).toUpperCase();
  7458. }
  7459. return str.toUpperCase();
  7460. };
  7461. /**
  7462. * Returns -1 if value is negative and +1 is value is positive.
  7463. * Returns the value itself if it's equal to zero.
  7464. */
  7465. Scalar.Sign = function (value) {
  7466. value = +value; // convert to a number
  7467. if (value === 0 || isNaN(value))
  7468. return value;
  7469. return value > 0 ? 1 : -1;
  7470. };
  7471. /**
  7472. * Returns the value itself if it's between min and max.
  7473. * Returns min if the value is lower than min.
  7474. * Returns max if the value is greater than max.
  7475. */
  7476. Scalar.Clamp = function (value, min, max) {
  7477. if (min === void 0) { min = 0; }
  7478. if (max === void 0) { max = 1; }
  7479. return Math.min(max, Math.max(min, value));
  7480. };
  7481. /**
  7482. * Returns the log2 of value.
  7483. */
  7484. Scalar.Log2 = function (value) {
  7485. return Math.log(value) * Math.LOG2E;
  7486. };
  7487. /**
  7488. * Loops the value, so that it is never larger than length and never smaller than 0.
  7489. *
  7490. * This is similar to the modulo operator but it works with floating point numbers.
  7491. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7492. * With t = 5 and length = 2.5, the result would be 0.0.
  7493. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7494. */
  7495. Scalar.Repeat = function (value, length) {
  7496. return value - Math.floor(value / length) * length;
  7497. };
  7498. /**
  7499. * Normalize the value between 0.0 and 1.0 using min and max values
  7500. */
  7501. Scalar.Normalize = function (value, min, max) {
  7502. return (value - min) / (max - min);
  7503. };
  7504. /**
  7505. * Denormalize the value from 0.0 and 1.0 using min and max values
  7506. */
  7507. Scalar.Denormalize = function (normalized, min, max) {
  7508. return (normalized * (max - min) + min);
  7509. };
  7510. /**
  7511. * Calculates the shortest difference between two given angles given in degrees.
  7512. */
  7513. Scalar.DeltaAngle = function (current, target) {
  7514. var num = Scalar.Repeat(target - current, 360.0);
  7515. if (num > 180.0) {
  7516. num -= 360.0;
  7517. }
  7518. return num;
  7519. };
  7520. /**
  7521. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7522. *
  7523. * The returned value will move back and forth between 0 and length
  7524. */
  7525. Scalar.PingPong = function (tx, length) {
  7526. var t = Scalar.Repeat(tx, length * 2.0);
  7527. return length - Math.abs(t - length);
  7528. };
  7529. /**
  7530. * Interpolates between min and max with smoothing at the limits.
  7531. *
  7532. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7533. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7534. */
  7535. Scalar.SmoothStep = function (from, to, tx) {
  7536. var t = Scalar.Clamp(tx);
  7537. t = -2.0 * t * t * t + 3.0 * t * t;
  7538. return to * t + from * (1.0 - t);
  7539. };
  7540. /**
  7541. * Moves a value current towards target.
  7542. *
  7543. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7544. * Negative values of maxDelta pushes the value away from target.
  7545. */
  7546. Scalar.MoveTowards = function (current, target, maxDelta) {
  7547. var result = 0;
  7548. if (Math.abs(target - current) <= maxDelta) {
  7549. result = target;
  7550. }
  7551. else {
  7552. result = current + Scalar.Sign(target - current) * maxDelta;
  7553. }
  7554. return result;
  7555. };
  7556. /**
  7557. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7558. *
  7559. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7560. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7561. */
  7562. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7563. var num = Scalar.DeltaAngle(current, target);
  7564. var result = 0;
  7565. if (-maxDelta < num && num < maxDelta) {
  7566. result = target;
  7567. }
  7568. else {
  7569. target = current + num;
  7570. result = Scalar.MoveTowards(current, target, maxDelta);
  7571. }
  7572. return result;
  7573. };
  7574. /**
  7575. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7576. */
  7577. Scalar.Lerp = function (start, end, amount) {
  7578. return start + ((end - start) * amount);
  7579. };
  7580. /**
  7581. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7582. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7583. */
  7584. Scalar.LerpAngle = function (start, end, amount) {
  7585. var num = Scalar.Repeat(end - start, 360.0);
  7586. if (num > 180.0) {
  7587. num -= 360.0;
  7588. }
  7589. return start + num * Scalar.Clamp(amount);
  7590. };
  7591. /**
  7592. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7593. */
  7594. Scalar.InverseLerp = function (a, b, value) {
  7595. var result = 0;
  7596. if (a != b) {
  7597. result = Scalar.Clamp((value - a) / (b - a));
  7598. }
  7599. else {
  7600. result = 0.0;
  7601. }
  7602. return result;
  7603. };
  7604. /**
  7605. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7606. */
  7607. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7608. var squared = amount * amount;
  7609. var cubed = amount * squared;
  7610. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7611. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7612. var part3 = (cubed - (2.0 * squared)) + amount;
  7613. var part4 = cubed - squared;
  7614. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7615. };
  7616. /**
  7617. * Returns a random float number between and min and max values
  7618. */
  7619. Scalar.RandomRange = function (min, max) {
  7620. if (min === max)
  7621. return min;
  7622. return ((Math.random() * (max - min)) + min);
  7623. };
  7624. /**
  7625. * This function returns percentage of a number in a given range.
  7626. *
  7627. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7628. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7629. */
  7630. Scalar.RangeToPercent = function (number, min, max) {
  7631. return ((number - min) / (max - min));
  7632. };
  7633. /**
  7634. * This function returns number that corresponds to the percentage in a given range.
  7635. *
  7636. * PercentToRange(0.34,0,100) will return 34.
  7637. */
  7638. Scalar.PercentToRange = function (percent, min, max) {
  7639. return ((max - min) * percent + min);
  7640. };
  7641. /**
  7642. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7643. * @param angle The angle to normalize in radian.
  7644. * @return The converted angle.
  7645. */
  7646. Scalar.NormalizeRadians = function (angle) {
  7647. // More precise but slower version kept for reference.
  7648. // angle = angle % Tools.TwoPi;
  7649. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7650. //if (angle > Math.PI) {
  7651. // angle -= Tools.TwoPi;
  7652. //}
  7653. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7654. return angle;
  7655. };
  7656. /**
  7657. * Two pi constants convenient for computation.
  7658. */
  7659. Scalar.TwoPi = Math.PI * 2;
  7660. return Scalar;
  7661. }());
  7662. BABYLON.Scalar = Scalar;
  7663. })(BABYLON || (BABYLON = {}));
  7664. //# sourceMappingURL=babylon.math.scalar.js.map
  7665. //# sourceMappingURL=babylon.mixins.js.map
  7666. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7667. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7668. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7669. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7670. //# sourceMappingURL=babylon.webgl2.js.map
  7671. var BABYLON;
  7672. (function (BABYLON) {
  7673. var __decoratorInitialStore = {};
  7674. var __mergedStore = {};
  7675. var _copySource = function (creationFunction, source, instanciate) {
  7676. var destination = creationFunction();
  7677. // Tags
  7678. if (BABYLON.Tags) {
  7679. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7680. }
  7681. var classStore = getMergedStore(destination);
  7682. // Properties
  7683. for (var property in classStore) {
  7684. var propertyDescriptor = classStore[property];
  7685. var sourceProperty = source[property];
  7686. var propertyType = propertyDescriptor.type;
  7687. if (sourceProperty !== undefined && sourceProperty !== null) {
  7688. switch (propertyType) {
  7689. case 0: // Value
  7690. case 6: // Mesh reference
  7691. case 11: // Camera reference
  7692. destination[property] = sourceProperty;
  7693. break;
  7694. case 1: // Texture
  7695. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7696. break;
  7697. case 2: // Color3
  7698. case 3: // FresnelParameters
  7699. case 4: // Vector2
  7700. case 5: // Vector3
  7701. case 7: // Color Curves
  7702. case 10: // Quaternion
  7703. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7704. break;
  7705. }
  7706. }
  7707. }
  7708. return destination;
  7709. };
  7710. function getDirectStore(target) {
  7711. var classKey = target.getClassName();
  7712. if (!__decoratorInitialStore[classKey]) {
  7713. __decoratorInitialStore[classKey] = {};
  7714. }
  7715. return __decoratorInitialStore[classKey];
  7716. }
  7717. /**
  7718. * Return the list of properties flagged as serializable
  7719. * @param target: host object
  7720. */
  7721. function getMergedStore(target) {
  7722. var classKey = target.getClassName();
  7723. if (__mergedStore[classKey]) {
  7724. return __mergedStore[classKey];
  7725. }
  7726. __mergedStore[classKey] = {};
  7727. var store = __mergedStore[classKey];
  7728. var currentTarget = target;
  7729. var currentKey = classKey;
  7730. while (currentKey) {
  7731. var initialStore = __decoratorInitialStore[currentKey];
  7732. for (var property in initialStore) {
  7733. store[property] = initialStore[property];
  7734. }
  7735. var parent_1 = void 0;
  7736. var done = false;
  7737. do {
  7738. parent_1 = Object.getPrototypeOf(currentTarget);
  7739. if (!parent_1.getClassName) {
  7740. done = true;
  7741. break;
  7742. }
  7743. if (parent_1.getClassName() !== currentKey) {
  7744. break;
  7745. }
  7746. currentTarget = parent_1;
  7747. } while (parent_1);
  7748. if (done) {
  7749. break;
  7750. }
  7751. currentKey = parent_1.getClassName();
  7752. currentTarget = parent_1;
  7753. }
  7754. return store;
  7755. }
  7756. function generateSerializableMember(type, sourceName) {
  7757. return function (target, propertyKey) {
  7758. var classStore = getDirectStore(target);
  7759. if (!classStore[propertyKey]) {
  7760. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7761. }
  7762. };
  7763. }
  7764. function generateExpandMember(setCallback, targetKey) {
  7765. if (targetKey === void 0) { targetKey = null; }
  7766. return function (target, propertyKey) {
  7767. var key = targetKey || ("_" + propertyKey);
  7768. Object.defineProperty(target, propertyKey, {
  7769. get: function () {
  7770. return this[key];
  7771. },
  7772. set: function (value) {
  7773. if (this[key] === value) {
  7774. return;
  7775. }
  7776. this[key] = value;
  7777. target[setCallback].apply(this);
  7778. },
  7779. enumerable: true,
  7780. configurable: true
  7781. });
  7782. };
  7783. }
  7784. function expandToProperty(callback, targetKey) {
  7785. if (targetKey === void 0) { targetKey = null; }
  7786. return generateExpandMember(callback, targetKey);
  7787. }
  7788. BABYLON.expandToProperty = expandToProperty;
  7789. function serialize(sourceName) {
  7790. return generateSerializableMember(0, sourceName); // value member
  7791. }
  7792. BABYLON.serialize = serialize;
  7793. function serializeAsTexture(sourceName) {
  7794. return generateSerializableMember(1, sourceName); // texture member
  7795. }
  7796. BABYLON.serializeAsTexture = serializeAsTexture;
  7797. function serializeAsColor3(sourceName) {
  7798. return generateSerializableMember(2, sourceName); // color3 member
  7799. }
  7800. BABYLON.serializeAsColor3 = serializeAsColor3;
  7801. function serializeAsFresnelParameters(sourceName) {
  7802. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7803. }
  7804. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7805. function serializeAsVector2(sourceName) {
  7806. return generateSerializableMember(4, sourceName); // vector2 member
  7807. }
  7808. BABYLON.serializeAsVector2 = serializeAsVector2;
  7809. function serializeAsVector3(sourceName) {
  7810. return generateSerializableMember(5, sourceName); // vector3 member
  7811. }
  7812. BABYLON.serializeAsVector3 = serializeAsVector3;
  7813. function serializeAsMeshReference(sourceName) {
  7814. return generateSerializableMember(6, sourceName); // mesh reference member
  7815. }
  7816. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7817. function serializeAsColorCurves(sourceName) {
  7818. return generateSerializableMember(7, sourceName); // color curves
  7819. }
  7820. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7821. function serializeAsColor4(sourceName) {
  7822. return generateSerializableMember(8, sourceName); // color 4
  7823. }
  7824. BABYLON.serializeAsColor4 = serializeAsColor4;
  7825. function serializeAsImageProcessingConfiguration(sourceName) {
  7826. return generateSerializableMember(9, sourceName); // image processing
  7827. }
  7828. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7829. function serializeAsQuaternion(sourceName) {
  7830. return generateSerializableMember(10, sourceName); // quaternion member
  7831. }
  7832. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7833. /**
  7834. * Decorator used to define property that can be serialized as reference to a camera
  7835. * @param sourceName defines the name of the property to decorate
  7836. */
  7837. function serializeAsCameraReference(sourceName) {
  7838. return generateSerializableMember(11, sourceName); // camera reference member
  7839. }
  7840. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7841. var SerializationHelper = /** @class */ (function () {
  7842. function SerializationHelper() {
  7843. }
  7844. SerializationHelper.Serialize = function (entity, serializationObject) {
  7845. if (!serializationObject) {
  7846. serializationObject = {};
  7847. }
  7848. // Tags
  7849. if (BABYLON.Tags) {
  7850. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7851. }
  7852. var serializedProperties = getMergedStore(entity);
  7853. // Properties
  7854. for (var property in serializedProperties) {
  7855. var propertyDescriptor = serializedProperties[property];
  7856. var targetPropertyName = propertyDescriptor.sourceName || property;
  7857. var propertyType = propertyDescriptor.type;
  7858. var sourceProperty = entity[property];
  7859. if (sourceProperty !== undefined && sourceProperty !== null) {
  7860. switch (propertyType) {
  7861. case 0: // Value
  7862. serializationObject[targetPropertyName] = sourceProperty;
  7863. break;
  7864. case 1: // Texture
  7865. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7866. break;
  7867. case 2: // Color3
  7868. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7869. break;
  7870. case 3: // FresnelParameters
  7871. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7872. break;
  7873. case 4: // Vector2
  7874. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7875. break;
  7876. case 5: // Vector3
  7877. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7878. break;
  7879. case 6: // Mesh reference
  7880. serializationObject[targetPropertyName] = sourceProperty.id;
  7881. break;
  7882. case 7: // Color Curves
  7883. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7884. break;
  7885. case 8: // Color 4
  7886. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7887. break;
  7888. case 9: // Image Processing
  7889. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7890. break;
  7891. case 10: // Quaternion
  7892. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7893. break;
  7894. case 11: // Camera reference
  7895. serializationObject[targetPropertyName] = sourceProperty.id;
  7896. break;
  7897. }
  7898. }
  7899. }
  7900. return serializationObject;
  7901. };
  7902. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7903. if (rootUrl === void 0) { rootUrl = null; }
  7904. var destination = creationFunction();
  7905. if (!rootUrl) {
  7906. rootUrl = "";
  7907. }
  7908. // Tags
  7909. if (BABYLON.Tags) {
  7910. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7911. }
  7912. var classStore = getMergedStore(destination);
  7913. // Properties
  7914. for (var property in classStore) {
  7915. var propertyDescriptor = classStore[property];
  7916. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7917. var propertyType = propertyDescriptor.type;
  7918. if (sourceProperty !== undefined && sourceProperty !== null) {
  7919. var dest = destination;
  7920. switch (propertyType) {
  7921. case 0: // Value
  7922. dest[property] = sourceProperty;
  7923. break;
  7924. case 1: // Texture
  7925. if (scene) {
  7926. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7927. }
  7928. break;
  7929. case 2: // Color3
  7930. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7931. break;
  7932. case 3: // FresnelParameters
  7933. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7934. break;
  7935. case 4: // Vector2
  7936. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7937. break;
  7938. case 5: // Vector3
  7939. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7940. break;
  7941. case 6: // Mesh reference
  7942. if (scene) {
  7943. dest[property] = scene.getLastMeshByID(sourceProperty);
  7944. }
  7945. break;
  7946. case 7: // Color Curves
  7947. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7948. break;
  7949. case 8: // Color 4
  7950. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7951. break;
  7952. case 9: // Image Processing
  7953. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7954. break;
  7955. case 10: // Quaternion
  7956. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7957. break;
  7958. case 11: // Camera reference
  7959. if (scene) {
  7960. dest[property] = scene.getCameraByID(sourceProperty);
  7961. }
  7962. break;
  7963. }
  7964. }
  7965. }
  7966. return destination;
  7967. };
  7968. SerializationHelper.Clone = function (creationFunction, source) {
  7969. return _copySource(creationFunction, source, false);
  7970. };
  7971. SerializationHelper.Instanciate = function (creationFunction, source) {
  7972. return _copySource(creationFunction, source, true);
  7973. };
  7974. return SerializationHelper;
  7975. }());
  7976. BABYLON.SerializationHelper = SerializationHelper;
  7977. })(BABYLON || (BABYLON = {}));
  7978. //# sourceMappingURL=babylon.decorators.js.map
  7979. var BABYLON;
  7980. (function (BABYLON) {
  7981. /**
  7982. * Wrapper class for promise with external resolve and reject.
  7983. */
  7984. var Deferred = /** @class */ (function () {
  7985. /**
  7986. * Constructor for this deferred object.
  7987. */
  7988. function Deferred() {
  7989. var _this = this;
  7990. this.promise = new Promise(function (resolve, reject) {
  7991. _this._resolve = resolve;
  7992. _this._reject = reject;
  7993. });
  7994. }
  7995. Object.defineProperty(Deferred.prototype, "resolve", {
  7996. /**
  7997. * The resolve method of the promise associated with this deferred object.
  7998. */
  7999. get: function () {
  8000. return this._resolve;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Deferred.prototype, "reject", {
  8006. /**
  8007. * The reject method of the promise associated with this deferred object.
  8008. */
  8009. get: function () {
  8010. return this._reject;
  8011. },
  8012. enumerable: true,
  8013. configurable: true
  8014. });
  8015. return Deferred;
  8016. }());
  8017. BABYLON.Deferred = Deferred;
  8018. })(BABYLON || (BABYLON = {}));
  8019. //# sourceMappingURL=babylon.deferred.js.map
  8020. var BABYLON;
  8021. (function (BABYLON) {
  8022. /**
  8023. * A class serves as a medium between the observable and its observers
  8024. */
  8025. var EventState = /** @class */ (function () {
  8026. /**
  8027. * Create a new EventState
  8028. * @param mask defines the mask associated with this state
  8029. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8030. * @param target defines the original target of the state
  8031. * @param currentTarget defines the current target of the state
  8032. */
  8033. function EventState(mask, skipNextObservers, target, currentTarget) {
  8034. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8035. this.initalize(mask, skipNextObservers, target, currentTarget);
  8036. }
  8037. /**
  8038. * Initialize the current event state
  8039. * @param mask defines the mask associated with this state
  8040. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8041. * @param target defines the original target of the state
  8042. * @param currentTarget defines the current target of the state
  8043. * @returns the current event state
  8044. */
  8045. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8046. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8047. this.mask = mask;
  8048. this.skipNextObservers = skipNextObservers;
  8049. this.target = target;
  8050. this.currentTarget = currentTarget;
  8051. return this;
  8052. };
  8053. return EventState;
  8054. }());
  8055. BABYLON.EventState = EventState;
  8056. /**
  8057. * Represent an Observer registered to a given Observable object.
  8058. */
  8059. var Observer = /** @class */ (function () {
  8060. /**
  8061. * Creates a new observer
  8062. * @param callback defines the callback to call when the observer is notified
  8063. * @param mask defines the mask of the observer (used to filter notifications)
  8064. * @param scope defines the current scope used to restore the JS context
  8065. */
  8066. function Observer(
  8067. /**
  8068. * Defines the callback to call when the observer is notified
  8069. */
  8070. callback,
  8071. /**
  8072. * Defines the mask of the observer (used to filter notifications)
  8073. */
  8074. mask,
  8075. /**
  8076. * Defines the current scope used to restore the JS context
  8077. */
  8078. scope) {
  8079. if (scope === void 0) { scope = null; }
  8080. this.callback = callback;
  8081. this.mask = mask;
  8082. this.scope = scope;
  8083. /** @hidden */
  8084. this._willBeUnregistered = false;
  8085. /**
  8086. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8087. */
  8088. this.unregisterOnNextCall = false;
  8089. }
  8090. return Observer;
  8091. }());
  8092. BABYLON.Observer = Observer;
  8093. /**
  8094. * Represent a list of observers registered to multiple Observables object.
  8095. */
  8096. var MultiObserver = /** @class */ (function () {
  8097. function MultiObserver() {
  8098. }
  8099. /**
  8100. * Release associated resources
  8101. */
  8102. MultiObserver.prototype.dispose = function () {
  8103. if (this._observers && this._observables) {
  8104. for (var index = 0; index < this._observers.length; index++) {
  8105. this._observables[index].remove(this._observers[index]);
  8106. }
  8107. }
  8108. this._observers = null;
  8109. this._observables = null;
  8110. };
  8111. /**
  8112. * Raise a callback when one of the observable will notify
  8113. * @param observables defines a list of observables to watch
  8114. * @param callback defines the callback to call on notification
  8115. * @param mask defines the mask used to filter notifications
  8116. * @param scope defines the current scope used to restore the JS context
  8117. * @returns the new MultiObserver
  8118. */
  8119. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8120. if (mask === void 0) { mask = -1; }
  8121. if (scope === void 0) { scope = null; }
  8122. var result = new MultiObserver();
  8123. result._observers = new Array();
  8124. result._observables = observables;
  8125. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8126. var observable = observables_1[_i];
  8127. var observer = observable.add(callback, mask, false, scope);
  8128. if (observer) {
  8129. result._observers.push(observer);
  8130. }
  8131. }
  8132. return result;
  8133. };
  8134. return MultiObserver;
  8135. }());
  8136. BABYLON.MultiObserver = MultiObserver;
  8137. /**
  8138. * The Observable class is a simple implementation of the Observable pattern.
  8139. *
  8140. * 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.
  8141. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8142. * 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).
  8143. * 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.
  8144. */
  8145. var Observable = /** @class */ (function () {
  8146. /**
  8147. * Creates a new observable
  8148. * @param onObserverAdded defines a callback to call when a new observer is added
  8149. */
  8150. function Observable(onObserverAdded) {
  8151. this._observers = new Array();
  8152. this._eventState = new EventState(0);
  8153. if (onObserverAdded) {
  8154. this._onObserverAdded = onObserverAdded;
  8155. }
  8156. }
  8157. /**
  8158. * Create a new Observer with the specified callback
  8159. * @param callback the callback that will be executed for that Observer
  8160. * @param mask the mask used to filter observers
  8161. * @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.
  8162. * @param scope optional scope for the callback to be called from
  8163. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8164. * @returns the new observer created for the callback
  8165. */
  8166. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8167. if (mask === void 0) { mask = -1; }
  8168. if (insertFirst === void 0) { insertFirst = false; }
  8169. if (scope === void 0) { scope = null; }
  8170. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8171. if (!callback) {
  8172. return null;
  8173. }
  8174. var observer = new Observer(callback, mask, scope);
  8175. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8176. if (insertFirst) {
  8177. this._observers.unshift(observer);
  8178. }
  8179. else {
  8180. this._observers.push(observer);
  8181. }
  8182. if (this._onObserverAdded) {
  8183. this._onObserverAdded(observer);
  8184. }
  8185. return observer;
  8186. };
  8187. /**
  8188. * Create a new Observer with the specified callback and unregisters after the next notification
  8189. * @param callback the callback that will be executed for that Observer
  8190. * @returns the new observer created for the callback
  8191. */
  8192. Observable.prototype.addOnce = function (callback) {
  8193. return this.add(callback, undefined, undefined, undefined, true);
  8194. };
  8195. /**
  8196. * Remove an Observer from the Observable object
  8197. * @param observer the instance of the Observer to remove
  8198. * @returns false if it doesn't belong to this Observable
  8199. */
  8200. Observable.prototype.remove = function (observer) {
  8201. if (!observer) {
  8202. return false;
  8203. }
  8204. var index = this._observers.indexOf(observer);
  8205. if (index !== -1) {
  8206. this._deferUnregister(observer);
  8207. return true;
  8208. }
  8209. return false;
  8210. };
  8211. /**
  8212. * Remove a callback from the Observable object
  8213. * @param callback the callback to remove
  8214. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8215. * @returns false if it doesn't belong to this Observable
  8216. */
  8217. Observable.prototype.removeCallback = function (callback, scope) {
  8218. for (var index = 0; index < this._observers.length; index++) {
  8219. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8220. this._deferUnregister(this._observers[index]);
  8221. return true;
  8222. }
  8223. }
  8224. return false;
  8225. };
  8226. Observable.prototype._deferUnregister = function (observer) {
  8227. var _this = this;
  8228. observer.unregisterOnNextCall = false;
  8229. observer._willBeUnregistered = true;
  8230. BABYLON.Tools.SetImmediate(function () {
  8231. _this._remove(observer);
  8232. });
  8233. };
  8234. // This should only be called when not iterating over _observers to avoid callback skipping.
  8235. // Removes an observer from the _observer Array.
  8236. Observable.prototype._remove = function (observer) {
  8237. if (!observer) {
  8238. return false;
  8239. }
  8240. var index = this._observers.indexOf(observer);
  8241. if (index !== -1) {
  8242. this._observers.splice(index, 1);
  8243. return true;
  8244. }
  8245. return false;
  8246. };
  8247. /**
  8248. * Notify all Observers by calling their respective callback with the given data
  8249. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8250. * @param eventData defines the data to send to all observers
  8251. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8252. * @param target defines the original target of the state
  8253. * @param currentTarget defines the current target of the state
  8254. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8255. */
  8256. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8257. if (mask === void 0) { mask = -1; }
  8258. if (!this._observers.length) {
  8259. return true;
  8260. }
  8261. var state = this._eventState;
  8262. state.mask = mask;
  8263. state.target = target;
  8264. state.currentTarget = currentTarget;
  8265. state.skipNextObservers = false;
  8266. state.lastReturnValue = eventData;
  8267. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8268. var obs = _a[_i];
  8269. if (obs._willBeUnregistered) {
  8270. continue;
  8271. }
  8272. if (obs.mask & mask) {
  8273. if (obs.scope) {
  8274. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8275. }
  8276. else {
  8277. state.lastReturnValue = obs.callback(eventData, state);
  8278. }
  8279. if (obs.unregisterOnNextCall) {
  8280. this._deferUnregister(obs);
  8281. }
  8282. }
  8283. if (state.skipNextObservers) {
  8284. return false;
  8285. }
  8286. }
  8287. return true;
  8288. };
  8289. /**
  8290. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8291. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8292. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8293. * and it is crucial that all callbacks will be executed.
  8294. * The order of the callbacks is kept, callbacks are not executed parallel.
  8295. *
  8296. * @param eventData The data to be sent to each callback
  8297. * @param mask is used to filter observers defaults to -1
  8298. * @param target defines the callback target (see EventState)
  8299. * @param currentTarget defines he current object in the bubbling phase
  8300. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8301. */
  8302. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8303. var _this = this;
  8304. if (mask === void 0) { mask = -1; }
  8305. // create an empty promise
  8306. var p = Promise.resolve(eventData);
  8307. // no observers? return this promise.
  8308. if (!this._observers.length) {
  8309. return p;
  8310. }
  8311. var state = this._eventState;
  8312. state.mask = mask;
  8313. state.target = target;
  8314. state.currentTarget = currentTarget;
  8315. state.skipNextObservers = false;
  8316. // execute one callback after another (not using Promise.all, the order is important)
  8317. this._observers.forEach(function (obs) {
  8318. if (state.skipNextObservers) {
  8319. return;
  8320. }
  8321. if (obs._willBeUnregistered) {
  8322. return;
  8323. }
  8324. if (obs.mask & mask) {
  8325. if (obs.scope) {
  8326. p = p.then(function (lastReturnedValue) {
  8327. state.lastReturnValue = lastReturnedValue;
  8328. return obs.callback.apply(obs.scope, [eventData, state]);
  8329. });
  8330. }
  8331. else {
  8332. p = p.then(function (lastReturnedValue) {
  8333. state.lastReturnValue = lastReturnedValue;
  8334. return obs.callback(eventData, state);
  8335. });
  8336. }
  8337. if (obs.unregisterOnNextCall) {
  8338. _this._deferUnregister(obs);
  8339. }
  8340. }
  8341. });
  8342. // return the eventData
  8343. return p.then(function () { return eventData; });
  8344. };
  8345. /**
  8346. * Notify a specific observer
  8347. * @param observer defines the observer to notify
  8348. * @param eventData defines the data to be sent to each callback
  8349. * @param mask is used to filter observers defaults to -1
  8350. */
  8351. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8352. if (mask === void 0) { mask = -1; }
  8353. var state = this._eventState;
  8354. state.mask = mask;
  8355. state.skipNextObservers = false;
  8356. observer.callback(eventData, state);
  8357. };
  8358. /**
  8359. * Gets a boolean indicating if the observable has at least one observer
  8360. * @returns true is the Observable has at least one Observer registered
  8361. */
  8362. Observable.prototype.hasObservers = function () {
  8363. return this._observers.length > 0;
  8364. };
  8365. /**
  8366. * Clear the list of observers
  8367. */
  8368. Observable.prototype.clear = function () {
  8369. this._observers = new Array();
  8370. this._onObserverAdded = null;
  8371. };
  8372. /**
  8373. * Clone the current observable
  8374. * @returns a new observable
  8375. */
  8376. Observable.prototype.clone = function () {
  8377. var result = new Observable();
  8378. result._observers = this._observers.slice(0);
  8379. return result;
  8380. };
  8381. /**
  8382. * Does this observable handles observer registered with a given mask
  8383. * @param mask defines the mask to be tested
  8384. * @return whether or not one observer registered with the given mask is handeled
  8385. **/
  8386. Observable.prototype.hasSpecificMask = function (mask) {
  8387. if (mask === void 0) { mask = -1; }
  8388. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8389. var obs = _a[_i];
  8390. if (obs.mask & mask || obs.mask === mask) {
  8391. return true;
  8392. }
  8393. }
  8394. return false;
  8395. };
  8396. return Observable;
  8397. }());
  8398. BABYLON.Observable = Observable;
  8399. })(BABYLON || (BABYLON = {}));
  8400. //# sourceMappingURL=babylon.observable.js.map
  8401. var BABYLON;
  8402. (function (BABYLON) {
  8403. var SmartArray = /** @class */ (function () {
  8404. function SmartArray(capacity) {
  8405. this.length = 0;
  8406. this.data = new Array(capacity);
  8407. this._id = SmartArray._GlobalId++;
  8408. }
  8409. SmartArray.prototype.push = function (value) {
  8410. this.data[this.length++] = value;
  8411. if (this.length > this.data.length) {
  8412. this.data.length *= 2;
  8413. }
  8414. };
  8415. SmartArray.prototype.forEach = function (func) {
  8416. for (var index = 0; index < this.length; index++) {
  8417. func(this.data[index]);
  8418. }
  8419. };
  8420. SmartArray.prototype.sort = function (compareFn) {
  8421. this.data.sort(compareFn);
  8422. };
  8423. SmartArray.prototype.reset = function () {
  8424. this.length = 0;
  8425. };
  8426. SmartArray.prototype.dispose = function () {
  8427. this.reset();
  8428. if (this.data) {
  8429. this.data.length = 0;
  8430. this.data = [];
  8431. }
  8432. };
  8433. SmartArray.prototype.concat = function (array) {
  8434. if (array.length === 0) {
  8435. return;
  8436. }
  8437. if (this.length + array.length > this.data.length) {
  8438. this.data.length = (this.length + array.length) * 2;
  8439. }
  8440. for (var index = 0; index < array.length; index++) {
  8441. this.data[this.length++] = (array.data || array)[index];
  8442. }
  8443. };
  8444. SmartArray.prototype.indexOf = function (value) {
  8445. var position = this.data.indexOf(value);
  8446. if (position >= this.length) {
  8447. return -1;
  8448. }
  8449. return position;
  8450. };
  8451. SmartArray.prototype.contains = function (value) {
  8452. return this.data.indexOf(value) !== -1;
  8453. };
  8454. // Statics
  8455. SmartArray._GlobalId = 0;
  8456. return SmartArray;
  8457. }());
  8458. BABYLON.SmartArray = SmartArray;
  8459. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8460. __extends(SmartArrayNoDuplicate, _super);
  8461. function SmartArrayNoDuplicate() {
  8462. var _this = _super !== null && _super.apply(this, arguments) || this;
  8463. _this._duplicateId = 0;
  8464. return _this;
  8465. }
  8466. SmartArrayNoDuplicate.prototype.push = function (value) {
  8467. _super.prototype.push.call(this, value);
  8468. if (!value.__smartArrayFlags) {
  8469. value.__smartArrayFlags = {};
  8470. }
  8471. value.__smartArrayFlags[this._id] = this._duplicateId;
  8472. };
  8473. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8474. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8475. return false;
  8476. }
  8477. this.push(value);
  8478. return true;
  8479. };
  8480. SmartArrayNoDuplicate.prototype.reset = function () {
  8481. _super.prototype.reset.call(this);
  8482. this._duplicateId++;
  8483. };
  8484. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8485. if (array.length === 0) {
  8486. return;
  8487. }
  8488. if (this.length + array.length > this.data.length) {
  8489. this.data.length = (this.length + array.length) * 2;
  8490. }
  8491. for (var index = 0; index < array.length; index++) {
  8492. var item = (array.data || array)[index];
  8493. this.pushNoDuplicate(item);
  8494. }
  8495. };
  8496. return SmartArrayNoDuplicate;
  8497. }(SmartArray));
  8498. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8499. })(BABYLON || (BABYLON = {}));
  8500. //# sourceMappingURL=babylon.smartArray.js.map
  8501. var BABYLON;
  8502. (function (BABYLON) {
  8503. /** Class used to store color gradient */
  8504. var ColorGradient = /** @class */ (function () {
  8505. function ColorGradient() {
  8506. }
  8507. /**
  8508. * Will get a color picked randomly between color1 and color2.
  8509. * If color2 is undefined then color1 will be used
  8510. * @param result defines the target Color4 to store the result in
  8511. */
  8512. ColorGradient.prototype.getColorToRef = function (result) {
  8513. if (!this.color2) {
  8514. result.copyFrom(this.color1);
  8515. return;
  8516. }
  8517. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8518. };
  8519. return ColorGradient;
  8520. }());
  8521. BABYLON.ColorGradient = ColorGradient;
  8522. /** Class used to store factor gradient */
  8523. var FactorGradient = /** @class */ (function () {
  8524. function FactorGradient() {
  8525. }
  8526. /**
  8527. * Will get a number picked randomly between factor1 and factor2.
  8528. * If factor2 is undefined then factor1 will be used
  8529. * @returns the picked number
  8530. */
  8531. FactorGradient.prototype.getFactor = function () {
  8532. if (this.factor2 === undefined) {
  8533. return this.factor1;
  8534. }
  8535. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8536. };
  8537. return FactorGradient;
  8538. }());
  8539. BABYLON.FactorGradient = FactorGradient;
  8540. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8541. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8542. var LoadFileError = /** @class */ (function (_super) {
  8543. __extends(LoadFileError, _super);
  8544. function LoadFileError(message, request) {
  8545. var _this = _super.call(this, message) || this;
  8546. _this.request = request;
  8547. _this.name = "LoadFileError";
  8548. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8549. return _this;
  8550. }
  8551. // Polyfill for Object.setPrototypeOf if necessary.
  8552. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8553. return LoadFileError;
  8554. }(Error));
  8555. BABYLON.LoadFileError = LoadFileError;
  8556. var RetryStrategy = /** @class */ (function () {
  8557. function RetryStrategy() {
  8558. }
  8559. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8560. if (maxRetries === void 0) { maxRetries = 3; }
  8561. if (baseInterval === void 0) { baseInterval = 500; }
  8562. return function (url, request, retryIndex) {
  8563. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8564. return -1;
  8565. }
  8566. return Math.pow(2, retryIndex) * baseInterval;
  8567. };
  8568. };
  8569. return RetryStrategy;
  8570. }());
  8571. BABYLON.RetryStrategy = RetryStrategy;
  8572. // Screenshots
  8573. var screenshotCanvas;
  8574. var cloneValue = function (source, destinationObject) {
  8575. if (!source)
  8576. return null;
  8577. if (source instanceof BABYLON.Mesh) {
  8578. return null;
  8579. }
  8580. if (source instanceof BABYLON.SubMesh) {
  8581. return source.clone(destinationObject);
  8582. }
  8583. else if (source.clone) {
  8584. return source.clone();
  8585. }
  8586. return null;
  8587. };
  8588. var Tools = /** @class */ (function () {
  8589. function Tools() {
  8590. }
  8591. /**
  8592. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8593. * @param u defines the coordinate on X axis
  8594. * @param v defines the coordinate on Y axis
  8595. * @param width defines the width of the source data
  8596. * @param height defines the height of the source data
  8597. * @param pixels defines the source byte array
  8598. * @param color defines the output color
  8599. */
  8600. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8601. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8602. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8603. var position = (wrappedU + wrappedV * width) * 4;
  8604. color.r = pixels[position] / 255;
  8605. color.g = pixels[position + 1] / 255;
  8606. color.b = pixels[position + 2] / 255;
  8607. color.a = pixels[position + 3] / 255;
  8608. };
  8609. /**
  8610. * Interpolates between a and b via alpha
  8611. * @param a The lower value (returned when alpha = 0)
  8612. * @param b The upper value (returned when alpha = 1)
  8613. * @param alpha The interpolation-factor
  8614. * @return The mixed value
  8615. */
  8616. Tools.Mix = function (a, b, alpha) {
  8617. return a * (1 - alpha) + b * alpha;
  8618. };
  8619. Tools.Instantiate = function (className) {
  8620. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8621. return Tools.RegisteredExternalClasses[className];
  8622. }
  8623. var arr = className.split(".");
  8624. var fn = (window || this);
  8625. for (var i = 0, len = arr.length; i < len; i++) {
  8626. fn = fn[arr[i]];
  8627. }
  8628. if (typeof fn !== "function") {
  8629. return null;
  8630. }
  8631. return fn;
  8632. };
  8633. /**
  8634. * Provides a slice function that will work even on IE
  8635. * @param data defines the array to slice
  8636. * @param start defines the start of the data (optional)
  8637. * @param end defines the end of the data (optional)
  8638. * @returns the new sliced array
  8639. */
  8640. Tools.Slice = function (data, start, end) {
  8641. if (data.slice) {
  8642. return data.slice(start, end);
  8643. }
  8644. return Array.prototype.slice.call(data, start, end);
  8645. };
  8646. Tools.SetImmediate = function (action) {
  8647. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8648. window.setImmediate(action);
  8649. }
  8650. else {
  8651. setTimeout(action, 1);
  8652. }
  8653. };
  8654. Tools.IsExponentOfTwo = function (value) {
  8655. var count = 1;
  8656. do {
  8657. count *= 2;
  8658. } while (count < value);
  8659. return count === value;
  8660. };
  8661. /**
  8662. * Returns the nearest 32-bit single precision float representation of a Number
  8663. * @param value A Number. If the parameter is of a different type, it will get converted
  8664. * to a number or to NaN if it cannot be converted
  8665. * @returns number
  8666. */
  8667. Tools.FloatRound = function (value) {
  8668. if (Math.fround) {
  8669. return Math.fround(value);
  8670. }
  8671. return (Tools._tmpFloatArray[0] = value);
  8672. };
  8673. /**
  8674. * Find the next highest power of two.
  8675. * @param x Number to start search from.
  8676. * @return Next highest power of two.
  8677. */
  8678. Tools.CeilingPOT = function (x) {
  8679. x--;
  8680. x |= x >> 1;
  8681. x |= x >> 2;
  8682. x |= x >> 4;
  8683. x |= x >> 8;
  8684. x |= x >> 16;
  8685. x++;
  8686. return x;
  8687. };
  8688. /**
  8689. * Find the next lowest power of two.
  8690. * @param x Number to start search from.
  8691. * @return Next lowest power of two.
  8692. */
  8693. Tools.FloorPOT = function (x) {
  8694. x = x | (x >> 1);
  8695. x = x | (x >> 2);
  8696. x = x | (x >> 4);
  8697. x = x | (x >> 8);
  8698. x = x | (x >> 16);
  8699. return x - (x >> 1);
  8700. };
  8701. /**
  8702. * Find the nearest power of two.
  8703. * @param x Number to start search from.
  8704. * @return Next nearest power of two.
  8705. */
  8706. Tools.NearestPOT = function (x) {
  8707. var c = Tools.CeilingPOT(x);
  8708. var f = Tools.FloorPOT(x);
  8709. return (c - x) > (x - f) ? f : c;
  8710. };
  8711. Tools.GetExponentOfTwo = function (value, max, mode) {
  8712. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8713. var pot;
  8714. switch (mode) {
  8715. case BABYLON.Engine.SCALEMODE_FLOOR:
  8716. pot = Tools.FloorPOT(value);
  8717. break;
  8718. case BABYLON.Engine.SCALEMODE_NEAREST:
  8719. pot = Tools.NearestPOT(value);
  8720. break;
  8721. case BABYLON.Engine.SCALEMODE_CEILING:
  8722. default:
  8723. pot = Tools.CeilingPOT(value);
  8724. break;
  8725. }
  8726. return Math.min(pot, max);
  8727. };
  8728. Tools.GetFilename = function (path) {
  8729. var index = path.lastIndexOf("/");
  8730. if (index < 0)
  8731. return path;
  8732. return path.substring(index + 1);
  8733. };
  8734. /**
  8735. * Extracts the "folder" part of a path (everything before the filename).
  8736. * @param uri The URI to extract the info from
  8737. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8738. * @returns The "folder" part of the path
  8739. */
  8740. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8741. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8742. var index = uri.lastIndexOf("/");
  8743. if (index < 0) {
  8744. if (returnUnchangedIfNoSlash) {
  8745. return uri;
  8746. }
  8747. return "";
  8748. }
  8749. return uri.substring(0, index + 1);
  8750. };
  8751. Tools.GetDOMTextContent = function (element) {
  8752. var result = "";
  8753. var child = element.firstChild;
  8754. while (child) {
  8755. if (child.nodeType === 3) {
  8756. result += child.textContent;
  8757. }
  8758. child = child.nextSibling;
  8759. }
  8760. return result;
  8761. };
  8762. Tools.ToDegrees = function (angle) {
  8763. return angle * 180 / Math.PI;
  8764. };
  8765. Tools.ToRadians = function (angle) {
  8766. return angle * Math.PI / 180;
  8767. };
  8768. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8769. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8770. var output = "";
  8771. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8772. var i = 0;
  8773. var bytes = new Uint8Array(buffer);
  8774. while (i < bytes.length) {
  8775. chr1 = bytes[i++];
  8776. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8777. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8778. enc1 = chr1 >> 2;
  8779. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8780. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8781. enc4 = chr3 & 63;
  8782. if (isNaN(chr2)) {
  8783. enc3 = enc4 = 64;
  8784. }
  8785. else if (isNaN(chr3)) {
  8786. enc4 = 64;
  8787. }
  8788. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8789. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8790. }
  8791. return "data:image/png;base64," + output;
  8792. };
  8793. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8794. if (bias === void 0) { bias = null; }
  8795. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8796. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8797. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8798. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8799. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8800. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8801. }
  8802. if (bias) {
  8803. minimum.x -= minimum.x * bias.x + bias.y;
  8804. minimum.y -= minimum.y * bias.x + bias.y;
  8805. minimum.z -= minimum.z * bias.x + bias.y;
  8806. maximum.x += maximum.x * bias.x + bias.y;
  8807. maximum.y += maximum.y * bias.x + bias.y;
  8808. maximum.z += maximum.z * bias.x + bias.y;
  8809. }
  8810. return {
  8811. minimum: minimum,
  8812. maximum: maximum
  8813. };
  8814. };
  8815. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8816. if (bias === void 0) { bias = null; }
  8817. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8818. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8819. if (!stride) {
  8820. stride = 3;
  8821. }
  8822. for (var index = start; index < start + count; index++) {
  8823. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8824. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8825. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8826. }
  8827. if (bias) {
  8828. minimum.x -= minimum.x * bias.x + bias.y;
  8829. minimum.y -= minimum.y * bias.x + bias.y;
  8830. minimum.z -= minimum.z * bias.x + bias.y;
  8831. maximum.x += maximum.x * bias.x + bias.y;
  8832. maximum.y += maximum.y * bias.x + bias.y;
  8833. maximum.z += maximum.z * bias.x + bias.y;
  8834. }
  8835. return {
  8836. minimum: minimum,
  8837. maximum: maximum
  8838. };
  8839. };
  8840. Tools.Vector2ArrayFeeder = function (array) {
  8841. return function (index) {
  8842. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8843. var length = isFloatArray ? array.length / 2 : array.length;
  8844. if (index >= length) {
  8845. return null;
  8846. }
  8847. if (isFloatArray) {
  8848. var fa = array;
  8849. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8850. }
  8851. var a = array;
  8852. return a[index];
  8853. };
  8854. };
  8855. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8856. if (bias === void 0) { bias = null; }
  8857. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8858. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8859. var i = 0;
  8860. var cur = feeder(i++);
  8861. while (cur) {
  8862. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8863. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8864. cur = feeder(i++);
  8865. }
  8866. if (bias) {
  8867. minimum.x -= minimum.x * bias.x + bias.y;
  8868. minimum.y -= minimum.y * bias.x + bias.y;
  8869. maximum.x += maximum.x * bias.x + bias.y;
  8870. maximum.y += maximum.y * bias.x + bias.y;
  8871. }
  8872. return {
  8873. minimum: minimum,
  8874. maximum: maximum
  8875. };
  8876. };
  8877. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8878. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8879. return null;
  8880. return Array.isArray(obj) ? obj : [obj];
  8881. };
  8882. // Misc.
  8883. Tools.GetPointerPrefix = function () {
  8884. var eventPrefix = "pointer";
  8885. // Check if pointer events are supported
  8886. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8887. eventPrefix = "mouse";
  8888. }
  8889. return eventPrefix;
  8890. };
  8891. /**
  8892. * @param func - the function to be called
  8893. * @param requester - the object that will request the next frame. Falls back to window.
  8894. */
  8895. Tools.QueueNewFrame = function (func, requester) {
  8896. if (!Tools.IsWindowObjectExist()) {
  8897. return setTimeout(func, 16);
  8898. }
  8899. if (!requester) {
  8900. requester = window;
  8901. }
  8902. if (requester.requestAnimationFrame) {
  8903. return requester.requestAnimationFrame(func);
  8904. }
  8905. else if (requester.msRequestAnimationFrame) {
  8906. return requester.msRequestAnimationFrame(func);
  8907. }
  8908. else if (requester.webkitRequestAnimationFrame) {
  8909. return requester.webkitRequestAnimationFrame(func);
  8910. }
  8911. else if (requester.mozRequestAnimationFrame) {
  8912. return requester.mozRequestAnimationFrame(func);
  8913. }
  8914. else if (requester.oRequestAnimationFrame) {
  8915. return requester.oRequestAnimationFrame(func);
  8916. }
  8917. else {
  8918. return window.setTimeout(func, 16);
  8919. }
  8920. };
  8921. Tools.RequestFullscreen = function (element) {
  8922. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8923. if (!requestFunction)
  8924. return;
  8925. requestFunction.call(element);
  8926. };
  8927. Tools.ExitFullscreen = function () {
  8928. if (document.exitFullscreen) {
  8929. document.exitFullscreen();
  8930. }
  8931. else if (document.mozCancelFullScreen) {
  8932. document.mozCancelFullScreen();
  8933. }
  8934. else if (document.webkitCancelFullScreen) {
  8935. document.webkitCancelFullScreen();
  8936. }
  8937. else if (document.msCancelFullScreen) {
  8938. document.msCancelFullScreen();
  8939. }
  8940. };
  8941. Tools.SetCorsBehavior = function (url, element) {
  8942. if (url && url.indexOf("data:") === 0) {
  8943. return;
  8944. }
  8945. if (Tools.CorsBehavior) {
  8946. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8947. element.crossOrigin = Tools.CorsBehavior;
  8948. }
  8949. else {
  8950. var result = Tools.CorsBehavior(url);
  8951. if (result) {
  8952. element.crossOrigin = result;
  8953. }
  8954. }
  8955. }
  8956. };
  8957. // External files
  8958. Tools.CleanUrl = function (url) {
  8959. url = url.replace(/#/mg, "%23");
  8960. return url;
  8961. };
  8962. /**
  8963. * Loads an image as an HTMLImageElement.
  8964. * @param input url string, ArrayBuffer, or Blob to load
  8965. * @param onLoad callback called when the image successfully loads
  8966. * @param onError callback called when the image fails to load
  8967. * @param database database for caching
  8968. * @returns the HTMLImageElement of the loaded image
  8969. */
  8970. Tools.LoadImage = function (input, onLoad, onError, database) {
  8971. var url;
  8972. var usingObjectURL = false;
  8973. if (input instanceof ArrayBuffer) {
  8974. url = URL.createObjectURL(new Blob([input]));
  8975. usingObjectURL = true;
  8976. }
  8977. else if (input instanceof Blob) {
  8978. url = URL.createObjectURL(input);
  8979. usingObjectURL = true;
  8980. }
  8981. else {
  8982. url = Tools.CleanUrl(input);
  8983. url = Tools.PreprocessUrl(input);
  8984. }
  8985. var img = new Image();
  8986. Tools.SetCorsBehavior(url, img);
  8987. var loadHandler = function () {
  8988. if (usingObjectURL && img.src) {
  8989. URL.revokeObjectURL(img.src);
  8990. }
  8991. img.removeEventListener("load", loadHandler);
  8992. img.removeEventListener("error", errorHandler);
  8993. onLoad(img);
  8994. };
  8995. var errorHandler = function (err) {
  8996. if (usingObjectURL && img.src) {
  8997. URL.revokeObjectURL(img.src);
  8998. }
  8999. img.removeEventListener("load", loadHandler);
  9000. img.removeEventListener("error", errorHandler);
  9001. Tools.Error("Error while trying to load image: " + input);
  9002. if (onError) {
  9003. onError("Error while trying to load image: " + input, err);
  9004. }
  9005. };
  9006. img.addEventListener("load", loadHandler);
  9007. img.addEventListener("error", errorHandler);
  9008. var noIndexedDB = function () {
  9009. img.src = url;
  9010. };
  9011. var loadFromIndexedDB = function () {
  9012. if (database) {
  9013. database.loadImageFromDB(url, img);
  9014. }
  9015. };
  9016. //ANY database to do!
  9017. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9018. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9019. }
  9020. else {
  9021. if (url.indexOf("file:") !== -1) {
  9022. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9023. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9024. try {
  9025. var blobURL;
  9026. try {
  9027. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9028. }
  9029. catch (ex) {
  9030. // Chrome doesn't support oneTimeOnly parameter
  9031. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9032. }
  9033. img.src = blobURL;
  9034. usingObjectURL = true;
  9035. }
  9036. catch (e) {
  9037. img.src = "";
  9038. }
  9039. return img;
  9040. }
  9041. }
  9042. noIndexedDB();
  9043. }
  9044. return img;
  9045. };
  9046. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9047. url = Tools.CleanUrl(url);
  9048. url = Tools.PreprocessUrl(url);
  9049. // If file and file input are set
  9050. if (url.indexOf("file:") !== -1) {
  9051. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9052. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9053. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9054. }
  9055. }
  9056. var loadUrl = Tools.BaseUrl + url;
  9057. var aborted = false;
  9058. var fileRequest = {
  9059. onCompleteObservable: new BABYLON.Observable(),
  9060. abort: function () { return aborted = true; },
  9061. };
  9062. var requestFile = function () {
  9063. var request = new XMLHttpRequest();
  9064. var retryHandle = null;
  9065. fileRequest.abort = function () {
  9066. aborted = true;
  9067. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9068. request.abort();
  9069. }
  9070. if (retryHandle !== null) {
  9071. clearTimeout(retryHandle);
  9072. retryHandle = null;
  9073. }
  9074. };
  9075. var retryLoop = function (retryIndex) {
  9076. request.open('GET', loadUrl, true);
  9077. if (useArrayBuffer) {
  9078. request.responseType = "arraybuffer";
  9079. }
  9080. if (onProgress) {
  9081. request.addEventListener("progress", onProgress);
  9082. }
  9083. var onLoadEnd = function () {
  9084. request.removeEventListener("loadend", onLoadEnd);
  9085. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9086. fileRequest.onCompleteObservable.clear();
  9087. };
  9088. request.addEventListener("loadend", onLoadEnd);
  9089. var onReadyStateChange = function () {
  9090. if (aborted) {
  9091. return;
  9092. }
  9093. // In case of undefined state in some browsers.
  9094. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9095. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9096. request.removeEventListener("readystatechange", onReadyStateChange);
  9097. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9098. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9099. return;
  9100. }
  9101. var retryStrategy = Tools.DefaultRetryStrategy;
  9102. if (retryStrategy) {
  9103. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9104. if (waitTime !== -1) {
  9105. // Prevent the request from completing for retry.
  9106. request.removeEventListener("loadend", onLoadEnd);
  9107. request = new XMLHttpRequest();
  9108. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9109. return;
  9110. }
  9111. }
  9112. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9113. if (onError) {
  9114. onError(request, e);
  9115. }
  9116. else {
  9117. throw e;
  9118. }
  9119. }
  9120. };
  9121. request.addEventListener("readystatechange", onReadyStateChange);
  9122. request.send();
  9123. };
  9124. retryLoop(0);
  9125. };
  9126. // Caching all files
  9127. if (database && database.enableSceneOffline) {
  9128. var noIndexedDB_1 = function (request) {
  9129. if (request && request.status > 400) {
  9130. if (onError) {
  9131. onError(request);
  9132. }
  9133. }
  9134. else {
  9135. if (!aborted) {
  9136. requestFile();
  9137. }
  9138. }
  9139. };
  9140. var loadFromIndexedDB = function () {
  9141. // TODO: database needs to support aborting and should return a IFileRequest
  9142. if (aborted) {
  9143. return;
  9144. }
  9145. if (database) {
  9146. database.loadFileFromDB(url, function (data) {
  9147. if (!aborted) {
  9148. onSuccess(data);
  9149. }
  9150. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9151. }, onProgress ? function (event) {
  9152. if (!aborted) {
  9153. onProgress(event);
  9154. }
  9155. } : undefined, noIndexedDB_1, useArrayBuffer);
  9156. }
  9157. };
  9158. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9159. }
  9160. else {
  9161. requestFile();
  9162. }
  9163. return fileRequest;
  9164. };
  9165. /**
  9166. * Load a script (identified by an url). When the url returns, the
  9167. * content of this file is added into a new script element, attached to the DOM (body element)
  9168. */
  9169. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9170. var head = document.getElementsByTagName('head')[0];
  9171. var script = document.createElement('script');
  9172. script.type = 'text/javascript';
  9173. script.src = scriptUrl;
  9174. script.onload = function () {
  9175. if (onSuccess) {
  9176. onSuccess();
  9177. }
  9178. };
  9179. script.onerror = function (e) {
  9180. if (onError) {
  9181. onError("Unable to load script '" + scriptUrl + "'", e);
  9182. }
  9183. };
  9184. head.appendChild(script);
  9185. };
  9186. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9187. var reader = new FileReader();
  9188. var request = {
  9189. onCompleteObservable: new BABYLON.Observable(),
  9190. abort: function () { return reader.abort(); },
  9191. };
  9192. reader.onloadend = function (e) {
  9193. request.onCompleteObservable.notifyObservers(request);
  9194. };
  9195. reader.onload = function (e) {
  9196. //target doesn't have result from ts 1.3
  9197. callback(e.target['result']);
  9198. };
  9199. reader.onprogress = progressCallback;
  9200. reader.readAsDataURL(fileToLoad);
  9201. return request;
  9202. };
  9203. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9204. var reader = new FileReader();
  9205. var request = {
  9206. onCompleteObservable: new BABYLON.Observable(),
  9207. abort: function () { return reader.abort(); },
  9208. };
  9209. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9210. reader.onerror = function (e) {
  9211. Tools.Log("Error while reading file: " + fileToLoad.name);
  9212. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9213. };
  9214. reader.onload = function (e) {
  9215. //target doesn't have result from ts 1.3
  9216. callback(e.target['result']);
  9217. };
  9218. if (progressCallBack) {
  9219. reader.onprogress = progressCallBack;
  9220. }
  9221. if (!useArrayBuffer) {
  9222. // Asynchronous read
  9223. reader.readAsText(fileToLoad);
  9224. }
  9225. else {
  9226. reader.readAsArrayBuffer(fileToLoad);
  9227. }
  9228. return request;
  9229. };
  9230. //returns a downloadable url to a file content.
  9231. Tools.FileAsURL = function (content) {
  9232. var fileBlob = new Blob([content]);
  9233. var url = window.URL || window.webkitURL;
  9234. var link = url.createObjectURL(fileBlob);
  9235. return link;
  9236. };
  9237. // Misc.
  9238. Tools.Format = function (value, decimals) {
  9239. if (decimals === void 0) { decimals = 2; }
  9240. return value.toFixed(decimals);
  9241. };
  9242. Tools.CheckExtends = function (v, min, max) {
  9243. if (v.x < min.x)
  9244. min.x = v.x;
  9245. if (v.y < min.y)
  9246. min.y = v.y;
  9247. if (v.z < min.z)
  9248. min.z = v.z;
  9249. if (v.x > max.x)
  9250. max.x = v.x;
  9251. if (v.y > max.y)
  9252. max.y = v.y;
  9253. if (v.z > max.z)
  9254. max.z = v.z;
  9255. };
  9256. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9257. for (var prop in source) {
  9258. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9259. continue;
  9260. }
  9261. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9262. continue;
  9263. }
  9264. var sourceValue = source[prop];
  9265. var typeOfSourceValue = typeof sourceValue;
  9266. if (typeOfSourceValue === "function") {
  9267. continue;
  9268. }
  9269. try {
  9270. if (typeOfSourceValue === "object") {
  9271. if (sourceValue instanceof Array) {
  9272. destination[prop] = [];
  9273. if (sourceValue.length > 0) {
  9274. if (typeof sourceValue[0] == "object") {
  9275. for (var index = 0; index < sourceValue.length; index++) {
  9276. var clonedValue = cloneValue(sourceValue[index], destination);
  9277. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9278. destination[prop].push(clonedValue);
  9279. }
  9280. }
  9281. }
  9282. else {
  9283. destination[prop] = sourceValue.slice(0);
  9284. }
  9285. }
  9286. }
  9287. else {
  9288. destination[prop] = cloneValue(sourceValue, destination);
  9289. }
  9290. }
  9291. else {
  9292. destination[prop] = sourceValue;
  9293. }
  9294. }
  9295. catch (e) {
  9296. // Just ignore error (it could be because of a read-only property)
  9297. }
  9298. }
  9299. };
  9300. Tools.IsEmpty = function (obj) {
  9301. for (var i in obj) {
  9302. if (obj.hasOwnProperty(i)) {
  9303. return false;
  9304. }
  9305. }
  9306. return true;
  9307. };
  9308. Tools.RegisterTopRootEvents = function (events) {
  9309. for (var index = 0; index < events.length; index++) {
  9310. var event = events[index];
  9311. window.addEventListener(event.name, event.handler, false);
  9312. try {
  9313. if (window.parent) {
  9314. window.parent.addEventListener(event.name, event.handler, false);
  9315. }
  9316. }
  9317. catch (e) {
  9318. // Silently fails...
  9319. }
  9320. }
  9321. };
  9322. Tools.UnregisterTopRootEvents = function (events) {
  9323. for (var index = 0; index < events.length; index++) {
  9324. var event = events[index];
  9325. window.removeEventListener(event.name, event.handler);
  9326. try {
  9327. if (window.parent) {
  9328. window.parent.removeEventListener(event.name, event.handler);
  9329. }
  9330. }
  9331. catch (e) {
  9332. // Silently fails...
  9333. }
  9334. }
  9335. };
  9336. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9337. if (mimeType === void 0) { mimeType = "image/png"; }
  9338. // Read the contents of the framebuffer
  9339. var numberOfChannelsByLine = width * 4;
  9340. var halfHeight = height / 2;
  9341. //Reading datas from WebGL
  9342. var data = engine.readPixels(0, 0, width, height);
  9343. //To flip image on Y axis.
  9344. for (var i = 0; i < halfHeight; i++) {
  9345. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9346. var currentCell = j + i * numberOfChannelsByLine;
  9347. var targetLine = height - i - 1;
  9348. var targetCell = j + targetLine * numberOfChannelsByLine;
  9349. var temp = data[currentCell];
  9350. data[currentCell] = data[targetCell];
  9351. data[targetCell] = temp;
  9352. }
  9353. }
  9354. // Create a 2D canvas to store the result
  9355. if (!screenshotCanvas) {
  9356. screenshotCanvas = document.createElement('canvas');
  9357. }
  9358. screenshotCanvas.width = width;
  9359. screenshotCanvas.height = height;
  9360. var context = screenshotCanvas.getContext('2d');
  9361. if (context) {
  9362. // Copy the pixels to a 2D canvas
  9363. var imageData = context.createImageData(width, height);
  9364. var castData = (imageData.data);
  9365. castData.set(data);
  9366. context.putImageData(imageData, 0, 0);
  9367. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9368. }
  9369. };
  9370. /**
  9371. * Converts the canvas data to blob.
  9372. * This acts as a polyfill for browsers not supporting the to blob function.
  9373. * @param canvas Defines the canvas to extract the data from
  9374. * @param successCallback Defines the callback triggered once the data are available
  9375. * @param mimeType Defines the mime type of the result
  9376. */
  9377. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9378. if (mimeType === void 0) { mimeType = "image/png"; }
  9379. // We need HTMLCanvasElement.toBlob for HD screenshots
  9380. if (!canvas.toBlob) {
  9381. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9382. canvas.toBlob = function (callback, type, quality) {
  9383. var _this = this;
  9384. setTimeout(function () {
  9385. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9386. for (var i = 0; i < len; i++) {
  9387. arr[i] = binStr.charCodeAt(i);
  9388. }
  9389. callback(new Blob([arr]));
  9390. });
  9391. };
  9392. }
  9393. canvas.toBlob(function (blob) {
  9394. successCallback(blob);
  9395. }, mimeType);
  9396. };
  9397. /**
  9398. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9399. * @param successCallback Defines the callback triggered once the data are available
  9400. * @param mimeType Defines the mime type of the result
  9401. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9402. */
  9403. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9404. if (mimeType === void 0) { mimeType = "image/png"; }
  9405. if (successCallback) {
  9406. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9407. successCallback(base64Image);
  9408. }
  9409. else {
  9410. this.ToBlob(screenshotCanvas, function (blob) {
  9411. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9412. if (("download" in document.createElement("a"))) {
  9413. if (!fileName) {
  9414. var date = new Date();
  9415. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9416. fileName = "screenshot_" + stringDate + ".png";
  9417. }
  9418. Tools.Download(blob, fileName);
  9419. }
  9420. else {
  9421. var url = URL.createObjectURL(blob);
  9422. var newWindow = window.open("");
  9423. if (!newWindow)
  9424. return;
  9425. var img = newWindow.document.createElement("img");
  9426. img.onload = function () {
  9427. // no longer need to read the blob so it's revoked
  9428. URL.revokeObjectURL(url);
  9429. };
  9430. img.src = url;
  9431. newWindow.document.body.appendChild(img);
  9432. }
  9433. }, mimeType);
  9434. }
  9435. };
  9436. /**
  9437. * Downloads a blob in the browser
  9438. * @param blob defines the blob to download
  9439. * @param fileName defines the name of the downloaded file
  9440. */
  9441. Tools.Download = function (blob, fileName) {
  9442. if (navigator && navigator.msSaveBlob) {
  9443. navigator.msSaveBlob(blob, fileName);
  9444. return;
  9445. }
  9446. var url = window.URL.createObjectURL(blob);
  9447. var a = document.createElement("a");
  9448. document.body.appendChild(a);
  9449. a.style.display = "none";
  9450. a.href = url;
  9451. a.download = fileName;
  9452. a.addEventListener("click", function () {
  9453. if (a.parentElement) {
  9454. a.parentElement.removeChild(a);
  9455. }
  9456. });
  9457. a.click();
  9458. window.URL.revokeObjectURL(url);
  9459. };
  9460. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9461. if (mimeType === void 0) { mimeType = "image/png"; }
  9462. var width;
  9463. var height;
  9464. // If a precision value is specified
  9465. if (size.precision) {
  9466. width = Math.round(engine.getRenderWidth() * size.precision);
  9467. height = Math.round(width / engine.getAspectRatio(camera));
  9468. }
  9469. else if (size.width && size.height) {
  9470. width = size.width;
  9471. height = size.height;
  9472. }
  9473. //If passing only width, computing height to keep display canvas ratio.
  9474. else if (size.width && !size.height) {
  9475. width = size.width;
  9476. height = Math.round(width / engine.getAspectRatio(camera));
  9477. }
  9478. //If passing only height, computing width to keep display canvas ratio.
  9479. else if (size.height && !size.width) {
  9480. height = size.height;
  9481. width = Math.round(height * engine.getAspectRatio(camera));
  9482. }
  9483. //Assuming here that "size" parameter is a number
  9484. else if (!isNaN(size)) {
  9485. height = size;
  9486. width = size;
  9487. }
  9488. else {
  9489. Tools.Error("Invalid 'size' parameter !");
  9490. return;
  9491. }
  9492. if (!screenshotCanvas) {
  9493. screenshotCanvas = document.createElement('canvas');
  9494. }
  9495. screenshotCanvas.width = width;
  9496. screenshotCanvas.height = height;
  9497. var renderContext = screenshotCanvas.getContext("2d");
  9498. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9499. var newWidth = width;
  9500. var newHeight = newWidth / ratio;
  9501. if (newHeight > height) {
  9502. newHeight = height;
  9503. newWidth = newHeight * ratio;
  9504. }
  9505. var offsetX = Math.max(0, width - newWidth) / 2;
  9506. var offsetY = Math.max(0, height - newHeight) / 2;
  9507. var renderingCanvas = engine.getRenderingCanvas();
  9508. if (renderContext && renderingCanvas) {
  9509. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9510. }
  9511. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9512. };
  9513. /**
  9514. * Generates an image screenshot from the specified camera.
  9515. *
  9516. * @param engine The engine to use for rendering
  9517. * @param camera The camera to use for rendering
  9518. * @param size This parameter can be set to a single number or to an object with the
  9519. * following (optional) properties: precision, width, height. If a single number is passed,
  9520. * it will be used for both width and height. If an object is passed, the screenshot size
  9521. * will be derived from the parameters. The precision property is a multiplier allowing
  9522. * rendering at a higher or lower resolution.
  9523. * @param successCallback The callback receives a single parameter which contains the
  9524. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9525. * src parameter of an <img> to display it.
  9526. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9527. * Check your browser for supported MIME types.
  9528. * @param samples Texture samples (default: 1)
  9529. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9530. * @param fileName A name for for the downloaded file.
  9531. * @constructor
  9532. */
  9533. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9534. if (mimeType === void 0) { mimeType = "image/png"; }
  9535. if (samples === void 0) { samples = 1; }
  9536. if (antialiasing === void 0) { antialiasing = false; }
  9537. var width;
  9538. var height;
  9539. //If a precision value is specified
  9540. if (size.precision) {
  9541. width = Math.round(engine.getRenderWidth() * size.precision);
  9542. height = Math.round(width / engine.getAspectRatio(camera));
  9543. size = { width: width, height: height };
  9544. }
  9545. else if (size.width && size.height) {
  9546. width = size.width;
  9547. height = size.height;
  9548. }
  9549. //If passing only width, computing height to keep display canvas ratio.
  9550. else if (size.width && !size.height) {
  9551. width = size.width;
  9552. height = Math.round(width / engine.getAspectRatio(camera));
  9553. size = { width: width, height: height };
  9554. }
  9555. //If passing only height, computing width to keep display canvas ratio.
  9556. else if (size.height && !size.width) {
  9557. height = size.height;
  9558. width = Math.round(height * engine.getAspectRatio(camera));
  9559. size = { width: width, height: height };
  9560. }
  9561. //Assuming here that "size" parameter is a number
  9562. else if (!isNaN(size)) {
  9563. height = size;
  9564. width = size;
  9565. }
  9566. else {
  9567. Tools.Error("Invalid 'size' parameter !");
  9568. return;
  9569. }
  9570. var scene = camera.getScene();
  9571. var previousCamera = null;
  9572. if (scene.activeCamera !== camera) {
  9573. previousCamera = scene.activeCamera;
  9574. scene.activeCamera = camera;
  9575. }
  9576. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9577. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9578. texture.renderList = null;
  9579. texture.samples = samples;
  9580. if (antialiasing) {
  9581. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9582. }
  9583. texture.onAfterRenderObservable.add(function () {
  9584. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9585. });
  9586. scene.incrementRenderId();
  9587. scene.resetCachedMaterial();
  9588. texture.render(true);
  9589. texture.dispose();
  9590. if (previousCamera) {
  9591. scene.activeCamera = previousCamera;
  9592. }
  9593. camera.getProjectionMatrix(true); // Force cache refresh;
  9594. };
  9595. // XHR response validator for local file scenario
  9596. Tools.ValidateXHRData = function (xhr, dataType) {
  9597. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9598. if (dataType === void 0) { dataType = 7; }
  9599. try {
  9600. if (dataType & 1) {
  9601. if (xhr.responseText && xhr.responseText.length > 0) {
  9602. return true;
  9603. }
  9604. else if (dataType === 1) {
  9605. return false;
  9606. }
  9607. }
  9608. if (dataType & 2) {
  9609. // Check header width and height since there is no "TGA" magic number
  9610. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9611. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9612. return true;
  9613. }
  9614. else if (dataType === 2) {
  9615. return false;
  9616. }
  9617. }
  9618. if (dataType & 4) {
  9619. // Check for the "DDS" magic number
  9620. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9621. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9622. return true;
  9623. }
  9624. else {
  9625. return false;
  9626. }
  9627. }
  9628. }
  9629. catch (e) {
  9630. // Global protection
  9631. }
  9632. return false;
  9633. };
  9634. /**
  9635. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9636. * Be aware Math.random() could cause collisions, but:
  9637. * "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"
  9638. */
  9639. Tools.RandomId = function () {
  9640. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9641. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9642. return v.toString(16);
  9643. });
  9644. };
  9645. /**
  9646. * Test if the given uri is a base64 string.
  9647. * @param uri The uri to test
  9648. * @return True if the uri is a base64 string or false otherwise.
  9649. */
  9650. Tools.IsBase64 = function (uri) {
  9651. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9652. };
  9653. /**
  9654. * Decode the given base64 uri.
  9655. * @param uri The uri to decode
  9656. * @return The decoded base64 data.
  9657. */
  9658. Tools.DecodeBase64 = function (uri) {
  9659. var decodedString = atob(uri.split(",")[1]);
  9660. var bufferLength = decodedString.length;
  9661. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9662. for (var i = 0; i < bufferLength; i++) {
  9663. bufferView[i] = decodedString.charCodeAt(i);
  9664. }
  9665. return bufferView.buffer;
  9666. };
  9667. Object.defineProperty(Tools, "NoneLogLevel", {
  9668. get: function () {
  9669. return Tools._NoneLogLevel;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Object.defineProperty(Tools, "MessageLogLevel", {
  9675. get: function () {
  9676. return Tools._MessageLogLevel;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(Tools, "WarningLogLevel", {
  9682. get: function () {
  9683. return Tools._WarningLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Tools, "ErrorLogLevel", {
  9689. get: function () {
  9690. return Tools._ErrorLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "AllLogLevel", {
  9696. get: function () {
  9697. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Tools._AddLogEntry = function (entry) {
  9703. Tools._LogCache = entry + Tools._LogCache;
  9704. if (Tools.OnNewCacheEntry) {
  9705. Tools.OnNewCacheEntry(entry);
  9706. }
  9707. };
  9708. Tools._FormatMessage = function (message) {
  9709. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9710. var date = new Date();
  9711. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9712. };
  9713. Tools._LogDisabled = function (message) {
  9714. // nothing to do
  9715. };
  9716. Tools._LogEnabled = function (message) {
  9717. var formattedMessage = Tools._FormatMessage(message);
  9718. console.log("BJS - " + formattedMessage);
  9719. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9720. Tools._AddLogEntry(entry);
  9721. };
  9722. Tools._WarnDisabled = function (message) {
  9723. // nothing to do
  9724. };
  9725. Tools._WarnEnabled = function (message) {
  9726. var formattedMessage = Tools._FormatMessage(message);
  9727. console.warn("BJS - " + formattedMessage);
  9728. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9729. Tools._AddLogEntry(entry);
  9730. };
  9731. Tools._ErrorDisabled = function (message) {
  9732. // nothing to do
  9733. };
  9734. Tools._ErrorEnabled = function (message) {
  9735. Tools.errorsCount++;
  9736. var formattedMessage = Tools._FormatMessage(message);
  9737. console.error("BJS - " + formattedMessage);
  9738. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9739. Tools._AddLogEntry(entry);
  9740. };
  9741. Object.defineProperty(Tools, "LogCache", {
  9742. get: function () {
  9743. return Tools._LogCache;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Tools.ClearLogCache = function () {
  9749. Tools._LogCache = "";
  9750. Tools.errorsCount = 0;
  9751. };
  9752. Object.defineProperty(Tools, "LogLevels", {
  9753. set: function (level) {
  9754. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9755. Tools.Log = Tools._LogEnabled;
  9756. }
  9757. else {
  9758. Tools.Log = Tools._LogDisabled;
  9759. }
  9760. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9761. Tools.Warn = Tools._WarnEnabled;
  9762. }
  9763. else {
  9764. Tools.Warn = Tools._WarnDisabled;
  9765. }
  9766. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9767. Tools.Error = Tools._ErrorEnabled;
  9768. }
  9769. else {
  9770. Tools.Error = Tools._ErrorDisabled;
  9771. }
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Tools.IsWindowObjectExist = function () {
  9777. return (typeof window) !== "undefined";
  9778. };
  9779. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9780. get: function () {
  9781. return Tools._PerformanceNoneLogLevel;
  9782. },
  9783. enumerable: true,
  9784. configurable: true
  9785. });
  9786. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9787. get: function () {
  9788. return Tools._PerformanceUserMarkLogLevel;
  9789. },
  9790. enumerable: true,
  9791. configurable: true
  9792. });
  9793. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9794. get: function () {
  9795. return Tools._PerformanceConsoleLogLevel;
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9801. set: function (level) {
  9802. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9803. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9804. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9805. return;
  9806. }
  9807. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9808. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9809. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9810. return;
  9811. }
  9812. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9813. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9819. };
  9820. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9821. };
  9822. Tools._StartUserMark = function (counterName, condition) {
  9823. if (condition === void 0) { condition = true; }
  9824. if (!Tools._performance) {
  9825. if (!Tools.IsWindowObjectExist()) {
  9826. return;
  9827. }
  9828. Tools._performance = window.performance;
  9829. }
  9830. if (!condition || !Tools._performance.mark) {
  9831. return;
  9832. }
  9833. Tools._performance.mark(counterName + "-Begin");
  9834. };
  9835. Tools._EndUserMark = function (counterName, condition) {
  9836. if (condition === void 0) { condition = true; }
  9837. if (!condition || !Tools._performance.mark) {
  9838. return;
  9839. }
  9840. Tools._performance.mark(counterName + "-End");
  9841. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9842. };
  9843. Tools._StartPerformanceConsole = function (counterName, condition) {
  9844. if (condition === void 0) { condition = true; }
  9845. if (!condition) {
  9846. return;
  9847. }
  9848. Tools._StartUserMark(counterName, condition);
  9849. if (console.time) {
  9850. console.time(counterName);
  9851. }
  9852. };
  9853. Tools._EndPerformanceConsole = function (counterName, condition) {
  9854. if (condition === void 0) { condition = true; }
  9855. if (!condition) {
  9856. return;
  9857. }
  9858. Tools._EndUserMark(counterName, condition);
  9859. if (console.time) {
  9860. console.timeEnd(counterName);
  9861. }
  9862. };
  9863. Object.defineProperty(Tools, "Now", {
  9864. get: function () {
  9865. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9866. return window.performance.now();
  9867. }
  9868. return Date.now();
  9869. },
  9870. enumerable: true,
  9871. configurable: true
  9872. });
  9873. /**
  9874. * This method will return the name of the class used to create the instance of the given object.
  9875. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9876. * @param object the object to get the class name from
  9877. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9878. */
  9879. Tools.GetClassName = function (object, isType) {
  9880. if (isType === void 0) { isType = false; }
  9881. var name = null;
  9882. if (!isType && object.getClassName) {
  9883. name = object.getClassName();
  9884. }
  9885. else {
  9886. if (object instanceof Object) {
  9887. var classObj = isType ? object : Object.getPrototypeOf(object);
  9888. name = classObj.constructor["__bjsclassName__"];
  9889. }
  9890. if (!name) {
  9891. name = typeof object;
  9892. }
  9893. }
  9894. return name;
  9895. };
  9896. Tools.First = function (array, predicate) {
  9897. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9898. var el = array_1[_i];
  9899. if (predicate(el)) {
  9900. return el;
  9901. }
  9902. }
  9903. return null;
  9904. };
  9905. /**
  9906. * This method will return the name of the full name of the class, including its owning module (if any).
  9907. * 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).
  9908. * @param object the object to get the class name from
  9909. * @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.
  9910. */
  9911. Tools.getFullClassName = function (object, isType) {
  9912. if (isType === void 0) { isType = false; }
  9913. var className = null;
  9914. var moduleName = null;
  9915. if (!isType && object.getClassName) {
  9916. className = object.getClassName();
  9917. }
  9918. else {
  9919. if (object instanceof Object) {
  9920. var classObj = isType ? object : Object.getPrototypeOf(object);
  9921. className = classObj.constructor["__bjsclassName__"];
  9922. moduleName = classObj.constructor["__bjsmoduleName__"];
  9923. }
  9924. if (!className) {
  9925. className = typeof object;
  9926. }
  9927. }
  9928. if (!className) {
  9929. return null;
  9930. }
  9931. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9932. };
  9933. /**
  9934. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  9935. * @param array
  9936. */
  9937. Tools.arrayOrStringFeeder = function (array) {
  9938. return function (index) {
  9939. if (index >= array.length) {
  9940. return null;
  9941. }
  9942. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9943. if (val && val.getHashCode) {
  9944. val = val.getHashCode();
  9945. }
  9946. if (typeof val === "string") {
  9947. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9948. }
  9949. return val;
  9950. };
  9951. };
  9952. /**
  9953. * Compute the hashCode of a stream of number
  9954. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9955. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9956. * @return the hash code computed
  9957. */
  9958. Tools.hashCodeFromStream = function (feeder) {
  9959. // Based from here: http://stackoverflow.com/a/7616484/802124
  9960. var hash = 0;
  9961. var index = 0;
  9962. var chr = feeder(index++);
  9963. while (chr != null) {
  9964. hash = ((hash << 5) - hash) + chr;
  9965. hash |= 0; // Convert to 32bit integer
  9966. chr = feeder(index++);
  9967. }
  9968. return hash;
  9969. };
  9970. /**
  9971. * Returns a promise that resolves after the given amount of time.
  9972. * @param delay Number of milliseconds to delay
  9973. * @returns Promise that resolves after the given amount of time
  9974. */
  9975. Tools.DelayAsync = function (delay) {
  9976. return new Promise(function (resolve) {
  9977. setTimeout(function () {
  9978. resolve();
  9979. }, delay);
  9980. });
  9981. };
  9982. /**
  9983. * Gets the current gradient from an array of IValueGradient
  9984. * @param ratio defines the current ratio to get
  9985. * @param gradients defines the array of IValueGradient
  9986. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9987. */
  9988. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9989. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9990. var currentGradient = gradients[gradientIndex];
  9991. var nextGradient = gradients[gradientIndex + 1];
  9992. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9993. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9994. updateFunc(currentGradient, nextGradient, scale);
  9995. }
  9996. }
  9997. };
  9998. Tools.BaseUrl = "";
  9999. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10000. /**
  10001. * Default behaviour for cors in the application.
  10002. * It can be a string if the expected behavior is identical in the entire app.
  10003. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10004. */
  10005. Tools.CorsBehavior = "anonymous";
  10006. Tools.UseFallbackTexture = true;
  10007. /**
  10008. * Use this object to register external classes like custom textures or material
  10009. * to allow the laoders to instantiate them
  10010. */
  10011. Tools.RegisteredExternalClasses = {};
  10012. // Used in case of a texture loading problem
  10013. 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";
  10014. Tools._tmpFloatArray = new Float32Array(1);
  10015. Tools.PreprocessUrl = function (url) {
  10016. return url;
  10017. };
  10018. // Logs
  10019. Tools._NoneLogLevel = 0;
  10020. Tools._MessageLogLevel = 1;
  10021. Tools._WarningLogLevel = 2;
  10022. Tools._ErrorLogLevel = 4;
  10023. Tools._LogCache = "";
  10024. Tools.errorsCount = 0;
  10025. Tools.Log = Tools._LogEnabled;
  10026. Tools.Warn = Tools._WarnEnabled;
  10027. Tools.Error = Tools._ErrorEnabled;
  10028. // Performances
  10029. Tools._PerformanceNoneLogLevel = 0;
  10030. Tools._PerformanceUserMarkLogLevel = 1;
  10031. Tools._PerformanceConsoleLogLevel = 2;
  10032. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10033. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10034. return Tools;
  10035. }());
  10036. BABYLON.Tools = Tools;
  10037. /**
  10038. * This class is used to track a performance counter which is number based.
  10039. * The user has access to many properties which give statistics of different nature
  10040. *
  10041. * The implementer can track two kinds of Performance Counter: time and count
  10042. * 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.
  10043. * 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.
  10044. */
  10045. var PerfCounter = /** @class */ (function () {
  10046. function PerfCounter() {
  10047. this._startMonitoringTime = 0;
  10048. this._min = 0;
  10049. this._max = 0;
  10050. this._average = 0;
  10051. this._lastSecAverage = 0;
  10052. this._current = 0;
  10053. this._totalValueCount = 0;
  10054. this._totalAccumulated = 0;
  10055. this._lastSecAccumulated = 0;
  10056. this._lastSecTime = 0;
  10057. this._lastSecValueCount = 0;
  10058. }
  10059. Object.defineProperty(PerfCounter.prototype, "min", {
  10060. /**
  10061. * Returns the smallest value ever
  10062. */
  10063. get: function () {
  10064. return this._min;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. Object.defineProperty(PerfCounter.prototype, "max", {
  10070. /**
  10071. * Returns the biggest value ever
  10072. */
  10073. get: function () {
  10074. return this._max;
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(PerfCounter.prototype, "average", {
  10080. /**
  10081. * Returns the average value since the performance counter is running
  10082. */
  10083. get: function () {
  10084. return this._average;
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10090. /**
  10091. * Returns the average value of the last second the counter was monitored
  10092. */
  10093. get: function () {
  10094. return this._lastSecAverage;
  10095. },
  10096. enumerable: true,
  10097. configurable: true
  10098. });
  10099. Object.defineProperty(PerfCounter.prototype, "current", {
  10100. /**
  10101. * Returns the current value
  10102. */
  10103. get: function () {
  10104. return this._current;
  10105. },
  10106. enumerable: true,
  10107. configurable: true
  10108. });
  10109. Object.defineProperty(PerfCounter.prototype, "total", {
  10110. get: function () {
  10111. return this._totalAccumulated;
  10112. },
  10113. enumerable: true,
  10114. configurable: true
  10115. });
  10116. Object.defineProperty(PerfCounter.prototype, "count", {
  10117. get: function () {
  10118. return this._totalValueCount;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. /**
  10124. * Call this method to start monitoring a new frame.
  10125. * 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.
  10126. */
  10127. PerfCounter.prototype.fetchNewFrame = function () {
  10128. this._totalValueCount++;
  10129. this._current = 0;
  10130. this._lastSecValueCount++;
  10131. };
  10132. /**
  10133. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10134. * @param newCount the count value to add to the monitored count
  10135. * @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.
  10136. */
  10137. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10138. if (!PerfCounter.Enabled) {
  10139. return;
  10140. }
  10141. this._current += newCount;
  10142. if (fetchResult) {
  10143. this._fetchResult();
  10144. }
  10145. };
  10146. /**
  10147. * Start monitoring this performance counter
  10148. */
  10149. PerfCounter.prototype.beginMonitoring = function () {
  10150. if (!PerfCounter.Enabled) {
  10151. return;
  10152. }
  10153. this._startMonitoringTime = Tools.Now;
  10154. };
  10155. /**
  10156. * Compute the time lapsed since the previous beginMonitoring() call.
  10157. * @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
  10158. */
  10159. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10160. if (newFrame === void 0) { newFrame = true; }
  10161. if (!PerfCounter.Enabled) {
  10162. return;
  10163. }
  10164. if (newFrame) {
  10165. this.fetchNewFrame();
  10166. }
  10167. var currentTime = Tools.Now;
  10168. this._current = currentTime - this._startMonitoringTime;
  10169. if (newFrame) {
  10170. this._fetchResult();
  10171. }
  10172. };
  10173. PerfCounter.prototype._fetchResult = function () {
  10174. this._totalAccumulated += this._current;
  10175. this._lastSecAccumulated += this._current;
  10176. // Min/Max update
  10177. this._min = Math.min(this._min, this._current);
  10178. this._max = Math.max(this._max, this._current);
  10179. this._average = this._totalAccumulated / this._totalValueCount;
  10180. // Reset last sec?
  10181. var now = Tools.Now;
  10182. if ((now - this._lastSecTime) > 1000) {
  10183. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10184. this._lastSecTime = now;
  10185. this._lastSecAccumulated = 0;
  10186. this._lastSecValueCount = 0;
  10187. }
  10188. };
  10189. PerfCounter.Enabled = true;
  10190. return PerfCounter;
  10191. }());
  10192. BABYLON.PerfCounter = PerfCounter;
  10193. /**
  10194. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10195. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10196. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10197. * @param name The name of the class, case should be preserved
  10198. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10199. */
  10200. function className(name, module) {
  10201. return function (target) {
  10202. target["__bjsclassName__"] = name;
  10203. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10204. };
  10205. }
  10206. BABYLON.className = className;
  10207. /**
  10208. * An implementation of a loop for asynchronous functions.
  10209. */
  10210. var AsyncLoop = /** @class */ (function () {
  10211. /**
  10212. * Constroctor.
  10213. * @param iterations the number of iterations.
  10214. * @param _fn the function to run each iteration
  10215. * @param _successCallback the callback that will be called upon succesful execution
  10216. * @param offset starting offset.
  10217. */
  10218. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10219. if (offset === void 0) { offset = 0; }
  10220. this.iterations = iterations;
  10221. this._fn = _fn;
  10222. this._successCallback = _successCallback;
  10223. this.index = offset - 1;
  10224. this._done = false;
  10225. }
  10226. /**
  10227. * Execute the next iteration. Must be called after the last iteration was finished.
  10228. */
  10229. AsyncLoop.prototype.executeNext = function () {
  10230. if (!this._done) {
  10231. if (this.index + 1 < this.iterations) {
  10232. ++this.index;
  10233. this._fn(this);
  10234. }
  10235. else {
  10236. this.breakLoop();
  10237. }
  10238. }
  10239. };
  10240. /**
  10241. * Break the loop and run the success callback.
  10242. */
  10243. AsyncLoop.prototype.breakLoop = function () {
  10244. this._done = true;
  10245. this._successCallback();
  10246. };
  10247. /**
  10248. * Helper function
  10249. */
  10250. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10251. if (offset === void 0) { offset = 0; }
  10252. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10253. loop.executeNext();
  10254. return loop;
  10255. };
  10256. /**
  10257. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10258. * @param iterations total number of iterations
  10259. * @param syncedIterations number of synchronous iterations in each async iteration.
  10260. * @param fn the function to call each iteration.
  10261. * @param callback a success call back that will be called when iterating stops.
  10262. * @param breakFunction a break condition (optional)
  10263. * @param timeout timeout settings for the setTimeout function. default - 0.
  10264. * @constructor
  10265. */
  10266. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10267. if (timeout === void 0) { timeout = 0; }
  10268. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10269. if (breakFunction && breakFunction())
  10270. loop.breakLoop();
  10271. else {
  10272. setTimeout(function () {
  10273. for (var i = 0; i < syncedIterations; ++i) {
  10274. var iteration = (loop.index * syncedIterations) + i;
  10275. if (iteration >= iterations)
  10276. break;
  10277. fn(iteration);
  10278. if (breakFunction && breakFunction()) {
  10279. loop.breakLoop();
  10280. break;
  10281. }
  10282. }
  10283. loop.executeNext();
  10284. }, timeout);
  10285. }
  10286. }, callback);
  10287. };
  10288. return AsyncLoop;
  10289. }());
  10290. BABYLON.AsyncLoop = AsyncLoop;
  10291. })(BABYLON || (BABYLON = {}));
  10292. //# sourceMappingURL=babylon.tools.js.map
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var PromiseStates;
  10296. (function (PromiseStates) {
  10297. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10298. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10299. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10300. })(PromiseStates || (PromiseStates = {}));
  10301. var FulFillmentAgregator = /** @class */ (function () {
  10302. function FulFillmentAgregator() {
  10303. this.count = 0;
  10304. this.target = 0;
  10305. this.results = [];
  10306. }
  10307. return FulFillmentAgregator;
  10308. }());
  10309. var InternalPromise = /** @class */ (function () {
  10310. function InternalPromise(resolver) {
  10311. var _this = this;
  10312. this._state = PromiseStates.Pending;
  10313. this._children = new Array();
  10314. this._rejectWasConsumed = false;
  10315. if (!resolver) {
  10316. return;
  10317. }
  10318. try {
  10319. resolver(function (value) {
  10320. _this._resolve(value);
  10321. }, function (reason) {
  10322. _this._reject(reason);
  10323. });
  10324. }
  10325. catch (e) {
  10326. this._reject(e);
  10327. }
  10328. }
  10329. Object.defineProperty(InternalPromise.prototype, "_result", {
  10330. get: function () {
  10331. return this._resultValue;
  10332. },
  10333. set: function (value) {
  10334. this._resultValue = value;
  10335. if (this._parent && this._parent._result === undefined) {
  10336. this._parent._result = value;
  10337. }
  10338. },
  10339. enumerable: true,
  10340. configurable: true
  10341. });
  10342. InternalPromise.prototype.catch = function (onRejected) {
  10343. return this.then(undefined, onRejected);
  10344. };
  10345. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10346. var _this = this;
  10347. var newPromise = new InternalPromise();
  10348. newPromise._onFulfilled = onFulfilled;
  10349. newPromise._onRejected = onRejected;
  10350. // Composition
  10351. this._children.push(newPromise);
  10352. newPromise._parent = this;
  10353. if (this._state !== PromiseStates.Pending) {
  10354. BABYLON.Tools.SetImmediate(function () {
  10355. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10356. var returnedValue = newPromise._resolve(_this._result);
  10357. if (returnedValue !== undefined && returnedValue !== null) {
  10358. if (returnedValue._state !== undefined) {
  10359. var returnedPromise = returnedValue;
  10360. newPromise._children.push(returnedPromise);
  10361. returnedPromise._parent = newPromise;
  10362. newPromise = returnedPromise;
  10363. }
  10364. else {
  10365. newPromise._result = returnedValue;
  10366. }
  10367. }
  10368. }
  10369. else {
  10370. newPromise._reject(_this._reason);
  10371. }
  10372. });
  10373. }
  10374. return newPromise;
  10375. };
  10376. InternalPromise.prototype._moveChildren = function (children) {
  10377. var _this = this;
  10378. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10379. this._children.forEach(function (child) {
  10380. child._parent = _this;
  10381. });
  10382. if (this._state === PromiseStates.Fulfilled) {
  10383. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10384. var child = _b[_i];
  10385. child._resolve(this._result);
  10386. }
  10387. }
  10388. else if (this._state === PromiseStates.Rejected) {
  10389. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10390. var child = _d[_c];
  10391. child._reject(this._reason);
  10392. }
  10393. }
  10394. var _a;
  10395. };
  10396. InternalPromise.prototype._resolve = function (value) {
  10397. try {
  10398. this._state = PromiseStates.Fulfilled;
  10399. var returnedValue = null;
  10400. if (this._onFulfilled) {
  10401. returnedValue = this._onFulfilled(value);
  10402. }
  10403. if (returnedValue !== undefined && returnedValue !== null) {
  10404. if (returnedValue._state !== undefined) {
  10405. // Transmit children
  10406. var returnedPromise = returnedValue;
  10407. returnedPromise._parent = this;
  10408. returnedPromise._moveChildren(this._children);
  10409. value = returnedPromise._result;
  10410. }
  10411. else {
  10412. value = returnedValue;
  10413. }
  10414. }
  10415. this._result = value;
  10416. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10417. var child = _a[_i];
  10418. child._resolve(value);
  10419. }
  10420. this._children.length = 0;
  10421. delete this._onFulfilled;
  10422. delete this._onRejected;
  10423. }
  10424. catch (e) {
  10425. this._reject(e, true);
  10426. }
  10427. };
  10428. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10429. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10430. this._state = PromiseStates.Rejected;
  10431. this._reason = reason;
  10432. if (this._onRejected && !onLocalThrow) {
  10433. try {
  10434. this._onRejected(reason);
  10435. this._rejectWasConsumed = true;
  10436. }
  10437. catch (e) {
  10438. reason = e;
  10439. }
  10440. }
  10441. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10442. var child = _a[_i];
  10443. if (this._rejectWasConsumed) {
  10444. child._resolve(null);
  10445. }
  10446. else {
  10447. child._reject(reason);
  10448. }
  10449. }
  10450. this._children.length = 0;
  10451. delete this._onFulfilled;
  10452. delete this._onRejected;
  10453. };
  10454. InternalPromise.resolve = function (value) {
  10455. var newPromise = new InternalPromise();
  10456. newPromise._resolve(value);
  10457. return newPromise;
  10458. };
  10459. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10460. promise.then(function (value) {
  10461. agregator.results[index] = value;
  10462. agregator.count++;
  10463. if (agregator.count === agregator.target) {
  10464. agregator.rootPromise._resolve(agregator.results);
  10465. }
  10466. return null;
  10467. }, function (reason) {
  10468. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10469. agregator.rootPromise._reject(reason);
  10470. }
  10471. });
  10472. };
  10473. InternalPromise.all = function (promises) {
  10474. var newPromise = new InternalPromise();
  10475. var agregator = new FulFillmentAgregator();
  10476. agregator.target = promises.length;
  10477. agregator.rootPromise = newPromise;
  10478. if (promises.length) {
  10479. for (var index = 0; index < promises.length; index++) {
  10480. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10481. }
  10482. }
  10483. else {
  10484. newPromise._resolve([]);
  10485. }
  10486. return newPromise;
  10487. };
  10488. InternalPromise.race = function (promises) {
  10489. var newPromise = new InternalPromise();
  10490. if (promises.length) {
  10491. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10492. var promise = promises_1[_i];
  10493. promise.then(function (value) {
  10494. if (newPromise) {
  10495. newPromise._resolve(value);
  10496. newPromise = null;
  10497. }
  10498. return null;
  10499. }, function (reason) {
  10500. if (newPromise) {
  10501. newPromise._reject(reason);
  10502. newPromise = null;
  10503. }
  10504. });
  10505. }
  10506. }
  10507. return newPromise;
  10508. };
  10509. return InternalPromise;
  10510. }());
  10511. /**
  10512. * Helper class that provides a small promise polyfill
  10513. */
  10514. var PromisePolyfill = /** @class */ (function () {
  10515. function PromisePolyfill() {
  10516. }
  10517. /**
  10518. * Static function used to check if the polyfill is required
  10519. * If this is the case then the function will inject the polyfill to window.Promise
  10520. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10521. */
  10522. PromisePolyfill.Apply = function (force) {
  10523. if (force === void 0) { force = false; }
  10524. if (force || typeof Promise === 'undefined') {
  10525. var root = window;
  10526. root.Promise = InternalPromise;
  10527. }
  10528. };
  10529. return PromisePolyfill;
  10530. }());
  10531. BABYLON.PromisePolyfill = PromisePolyfill;
  10532. })(BABYLON || (BABYLON = {}));
  10533. //# sourceMappingURL=babylon.promise.js.map
  10534. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10535. var BABYLON;
  10536. (function (BABYLON) {
  10537. /**
  10538. * Helper class to push actions to a pool of workers.
  10539. */
  10540. var WorkerPool = /** @class */ (function () {
  10541. /**
  10542. * Constructor
  10543. * @param workers Array of workers to use for actions
  10544. */
  10545. function WorkerPool(workers) {
  10546. this._pendingActions = new Array();
  10547. this._workerInfos = workers.map(function (worker) { return ({
  10548. worker: worker,
  10549. active: false
  10550. }); });
  10551. }
  10552. /**
  10553. * Terminates all workers and clears any pending actions.
  10554. */
  10555. WorkerPool.prototype.dispose = function () {
  10556. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10557. var workerInfo = _a[_i];
  10558. workerInfo.worker.terminate();
  10559. }
  10560. delete this._workerInfos;
  10561. delete this._pendingActions;
  10562. };
  10563. /**
  10564. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10565. * pended until a worker has completed its action.
  10566. * @param action The action to perform. Call onComplete when the action is complete.
  10567. */
  10568. WorkerPool.prototype.push = function (action) {
  10569. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10570. var workerInfo = _a[_i];
  10571. if (!workerInfo.active) {
  10572. this._execute(workerInfo, action);
  10573. return;
  10574. }
  10575. }
  10576. this._pendingActions.push(action);
  10577. };
  10578. WorkerPool.prototype._execute = function (workerInfo, action) {
  10579. var _this = this;
  10580. workerInfo.active = true;
  10581. action(workerInfo.worker, function () {
  10582. workerInfo.active = false;
  10583. var nextAction = _this._pendingActions.shift();
  10584. if (nextAction) {
  10585. _this._execute(workerInfo, nextAction);
  10586. }
  10587. });
  10588. };
  10589. return WorkerPool;
  10590. }());
  10591. BABYLON.WorkerPool = WorkerPool;
  10592. })(BABYLON || (BABYLON = {}));
  10593. //# sourceMappingURL=babylon.workerPool.js.map
  10594. var BABYLON;
  10595. (function (BABYLON) {
  10596. /**
  10597. * @hidden
  10598. **/
  10599. var _AlphaState = /** @class */ (function () {
  10600. /**
  10601. * Initializes the state.
  10602. */
  10603. function _AlphaState() {
  10604. this._isAlphaBlendDirty = false;
  10605. this._isBlendFunctionParametersDirty = false;
  10606. this._isBlendEquationParametersDirty = false;
  10607. this._isBlendConstantsDirty = false;
  10608. this._alphaBlend = false;
  10609. this._blendFunctionParameters = new Array(4);
  10610. this._blendEquationParameters = new Array(2);
  10611. this._blendConstants = new Array(4);
  10612. this.reset();
  10613. }
  10614. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10615. get: function () {
  10616. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10622. get: function () {
  10623. return this._alphaBlend;
  10624. },
  10625. set: function (value) {
  10626. if (this._alphaBlend === value) {
  10627. return;
  10628. }
  10629. this._alphaBlend = value;
  10630. this._isAlphaBlendDirty = true;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10636. if (this._blendConstants[0] === r &&
  10637. this._blendConstants[1] === g &&
  10638. this._blendConstants[2] === b &&
  10639. this._blendConstants[3] === a) {
  10640. return;
  10641. }
  10642. this._blendConstants[0] = r;
  10643. this._blendConstants[1] = g;
  10644. this._blendConstants[2] = b;
  10645. this._blendConstants[3] = a;
  10646. this._isBlendConstantsDirty = true;
  10647. };
  10648. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10649. if (this._blendFunctionParameters[0] === value0 &&
  10650. this._blendFunctionParameters[1] === value1 &&
  10651. this._blendFunctionParameters[2] === value2 &&
  10652. this._blendFunctionParameters[3] === value3) {
  10653. return;
  10654. }
  10655. this._blendFunctionParameters[0] = value0;
  10656. this._blendFunctionParameters[1] = value1;
  10657. this._blendFunctionParameters[2] = value2;
  10658. this._blendFunctionParameters[3] = value3;
  10659. this._isBlendFunctionParametersDirty = true;
  10660. };
  10661. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10662. if (this._blendEquationParameters[0] === rgb &&
  10663. this._blendEquationParameters[1] === alpha) {
  10664. return;
  10665. }
  10666. this._blendEquationParameters[0] = rgb;
  10667. this._blendEquationParameters[1] = alpha;
  10668. this._isBlendEquationParametersDirty = true;
  10669. };
  10670. _AlphaState.prototype.reset = function () {
  10671. this._alphaBlend = false;
  10672. this._blendFunctionParameters[0] = null;
  10673. this._blendFunctionParameters[1] = null;
  10674. this._blendFunctionParameters[2] = null;
  10675. this._blendFunctionParameters[3] = null;
  10676. this._blendEquationParameters[0] = null;
  10677. this._blendEquationParameters[1] = null;
  10678. this._blendConstants[0] = null;
  10679. this._blendConstants[1] = null;
  10680. this._blendConstants[2] = null;
  10681. this._blendConstants[3] = null;
  10682. this._isAlphaBlendDirty = true;
  10683. this._isBlendFunctionParametersDirty = false;
  10684. this._isBlendEquationParametersDirty = false;
  10685. this._isBlendConstantsDirty = false;
  10686. };
  10687. _AlphaState.prototype.apply = function (gl) {
  10688. if (!this.isDirty) {
  10689. return;
  10690. }
  10691. // Alpha blend
  10692. if (this._isAlphaBlendDirty) {
  10693. if (this._alphaBlend) {
  10694. gl.enable(gl.BLEND);
  10695. }
  10696. else {
  10697. gl.disable(gl.BLEND);
  10698. }
  10699. this._isAlphaBlendDirty = false;
  10700. }
  10701. // Alpha function
  10702. if (this._isBlendFunctionParametersDirty) {
  10703. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10704. this._isBlendFunctionParametersDirty = false;
  10705. }
  10706. // Alpha equation
  10707. if (this._isBlendEquationParametersDirty) {
  10708. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10709. this._isBlendEquationParametersDirty = false;
  10710. }
  10711. // Constants
  10712. if (this._isBlendConstantsDirty) {
  10713. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10714. this._isBlendConstantsDirty = false;
  10715. }
  10716. };
  10717. return _AlphaState;
  10718. }());
  10719. BABYLON._AlphaState = _AlphaState;
  10720. })(BABYLON || (BABYLON = {}));
  10721. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10722. var BABYLON;
  10723. (function (BABYLON) {
  10724. /**
  10725. * @hidden
  10726. **/
  10727. var _DepthCullingState = /** @class */ (function () {
  10728. /**
  10729. * Initializes the state.
  10730. */
  10731. function _DepthCullingState() {
  10732. this._isDepthTestDirty = false;
  10733. this._isDepthMaskDirty = false;
  10734. this._isDepthFuncDirty = false;
  10735. this._isCullFaceDirty = false;
  10736. this._isCullDirty = false;
  10737. this._isZOffsetDirty = false;
  10738. this._isFrontFaceDirty = false;
  10739. this.reset();
  10740. }
  10741. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10742. get: function () {
  10743. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10749. get: function () {
  10750. return this._zOffset;
  10751. },
  10752. set: function (value) {
  10753. if (this._zOffset === value) {
  10754. return;
  10755. }
  10756. this._zOffset = value;
  10757. this._isZOffsetDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10763. get: function () {
  10764. return this._cullFace;
  10765. },
  10766. set: function (value) {
  10767. if (this._cullFace === value) {
  10768. return;
  10769. }
  10770. this._cullFace = value;
  10771. this._isCullFaceDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10777. get: function () {
  10778. return this._cull;
  10779. },
  10780. set: function (value) {
  10781. if (this._cull === value) {
  10782. return;
  10783. }
  10784. this._cull = value;
  10785. this._isCullDirty = true;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10791. get: function () {
  10792. return this._depthFunc;
  10793. },
  10794. set: function (value) {
  10795. if (this._depthFunc === value) {
  10796. return;
  10797. }
  10798. this._depthFunc = value;
  10799. this._isDepthFuncDirty = true;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10805. get: function () {
  10806. return this._depthMask;
  10807. },
  10808. set: function (value) {
  10809. if (this._depthMask === value) {
  10810. return;
  10811. }
  10812. this._depthMask = value;
  10813. this._isDepthMaskDirty = true;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10819. get: function () {
  10820. return this._depthTest;
  10821. },
  10822. set: function (value) {
  10823. if (this._depthTest === value) {
  10824. return;
  10825. }
  10826. this._depthTest = value;
  10827. this._isDepthTestDirty = true;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10833. get: function () {
  10834. return this._frontFace;
  10835. },
  10836. set: function (value) {
  10837. if (this._frontFace === value) {
  10838. return;
  10839. }
  10840. this._frontFace = value;
  10841. this._isFrontFaceDirty = true;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. _DepthCullingState.prototype.reset = function () {
  10847. this._depthMask = true;
  10848. this._depthTest = true;
  10849. this._depthFunc = null;
  10850. this._cullFace = null;
  10851. this._cull = null;
  10852. this._zOffset = 0;
  10853. this._frontFace = null;
  10854. this._isDepthTestDirty = true;
  10855. this._isDepthMaskDirty = true;
  10856. this._isDepthFuncDirty = false;
  10857. this._isCullFaceDirty = false;
  10858. this._isCullDirty = false;
  10859. this._isZOffsetDirty = false;
  10860. this._isFrontFaceDirty = false;
  10861. };
  10862. _DepthCullingState.prototype.apply = function (gl) {
  10863. if (!this.isDirty) {
  10864. return;
  10865. }
  10866. // Cull
  10867. if (this._isCullDirty) {
  10868. if (this.cull) {
  10869. gl.enable(gl.CULL_FACE);
  10870. }
  10871. else {
  10872. gl.disable(gl.CULL_FACE);
  10873. }
  10874. this._isCullDirty = false;
  10875. }
  10876. // Cull face
  10877. if (this._isCullFaceDirty) {
  10878. gl.cullFace(this.cullFace);
  10879. this._isCullFaceDirty = false;
  10880. }
  10881. // Depth mask
  10882. if (this._isDepthMaskDirty) {
  10883. gl.depthMask(this.depthMask);
  10884. this._isDepthMaskDirty = false;
  10885. }
  10886. // Depth test
  10887. if (this._isDepthTestDirty) {
  10888. if (this.depthTest) {
  10889. gl.enable(gl.DEPTH_TEST);
  10890. }
  10891. else {
  10892. gl.disable(gl.DEPTH_TEST);
  10893. }
  10894. this._isDepthTestDirty = false;
  10895. }
  10896. // Depth func
  10897. if (this._isDepthFuncDirty) {
  10898. gl.depthFunc(this.depthFunc);
  10899. this._isDepthFuncDirty = false;
  10900. }
  10901. // zOffset
  10902. if (this._isZOffsetDirty) {
  10903. if (this.zOffset) {
  10904. gl.enable(gl.POLYGON_OFFSET_FILL);
  10905. gl.polygonOffset(this.zOffset, 0);
  10906. }
  10907. else {
  10908. gl.disable(gl.POLYGON_OFFSET_FILL);
  10909. }
  10910. this._isZOffsetDirty = false;
  10911. }
  10912. // Front face
  10913. if (this._isFrontFaceDirty) {
  10914. gl.frontFace(this.frontFace);
  10915. this._isFrontFaceDirty = false;
  10916. }
  10917. };
  10918. return _DepthCullingState;
  10919. }());
  10920. BABYLON._DepthCullingState = _DepthCullingState;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.depthCullingState.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. /**
  10926. * @hidden
  10927. **/
  10928. var _StencilState = /** @class */ (function () {
  10929. function _StencilState() {
  10930. this._isStencilTestDirty = false;
  10931. this._isStencilMaskDirty = false;
  10932. this._isStencilFuncDirty = false;
  10933. this._isStencilOpDirty = false;
  10934. this.reset();
  10935. }
  10936. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10937. get: function () {
  10938. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10944. get: function () {
  10945. return this._stencilFunc;
  10946. },
  10947. set: function (value) {
  10948. if (this._stencilFunc === value) {
  10949. return;
  10950. }
  10951. this._stencilFunc = value;
  10952. this._isStencilFuncDirty = true;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10958. get: function () {
  10959. return this._stencilFuncRef;
  10960. },
  10961. set: function (value) {
  10962. if (this._stencilFuncRef === value) {
  10963. return;
  10964. }
  10965. this._stencilFuncRef = value;
  10966. this._isStencilFuncDirty = true;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10972. get: function () {
  10973. return this._stencilFuncMask;
  10974. },
  10975. set: function (value) {
  10976. if (this._stencilFuncMask === value) {
  10977. return;
  10978. }
  10979. this._stencilFuncMask = value;
  10980. this._isStencilFuncDirty = true;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10986. get: function () {
  10987. return this._stencilOpStencilFail;
  10988. },
  10989. set: function (value) {
  10990. if (this._stencilOpStencilFail === value) {
  10991. return;
  10992. }
  10993. this._stencilOpStencilFail = value;
  10994. this._isStencilOpDirty = true;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11000. get: function () {
  11001. return this._stencilOpDepthFail;
  11002. },
  11003. set: function (value) {
  11004. if (this._stencilOpDepthFail === value) {
  11005. return;
  11006. }
  11007. this._stencilOpDepthFail = value;
  11008. this._isStencilOpDirty = true;
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11014. get: function () {
  11015. return this._stencilOpStencilDepthPass;
  11016. },
  11017. set: function (value) {
  11018. if (this._stencilOpStencilDepthPass === value) {
  11019. return;
  11020. }
  11021. this._stencilOpStencilDepthPass = value;
  11022. this._isStencilOpDirty = true;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11028. get: function () {
  11029. return this._stencilMask;
  11030. },
  11031. set: function (value) {
  11032. if (this._stencilMask === value) {
  11033. return;
  11034. }
  11035. this._stencilMask = value;
  11036. this._isStencilMaskDirty = true;
  11037. },
  11038. enumerable: true,
  11039. configurable: true
  11040. });
  11041. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11042. get: function () {
  11043. return this._stencilTest;
  11044. },
  11045. set: function (value) {
  11046. if (this._stencilTest === value) {
  11047. return;
  11048. }
  11049. this._stencilTest = value;
  11050. this._isStencilTestDirty = true;
  11051. },
  11052. enumerable: true,
  11053. configurable: true
  11054. });
  11055. _StencilState.prototype.reset = function () {
  11056. this._stencilTest = false;
  11057. this._stencilMask = 0xFF;
  11058. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11059. this._stencilFuncRef = 1;
  11060. this._stencilFuncMask = 0xFF;
  11061. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11062. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11063. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11064. this._isStencilTestDirty = true;
  11065. this._isStencilMaskDirty = true;
  11066. this._isStencilFuncDirty = true;
  11067. this._isStencilOpDirty = true;
  11068. };
  11069. _StencilState.prototype.apply = function (gl) {
  11070. if (!this.isDirty) {
  11071. return;
  11072. }
  11073. // Stencil test
  11074. if (this._isStencilTestDirty) {
  11075. if (this.stencilTest) {
  11076. gl.enable(gl.STENCIL_TEST);
  11077. }
  11078. else {
  11079. gl.disable(gl.STENCIL_TEST);
  11080. }
  11081. this._isStencilTestDirty = false;
  11082. }
  11083. // Stencil mask
  11084. if (this._isStencilMaskDirty) {
  11085. gl.stencilMask(this.stencilMask);
  11086. this._isStencilMaskDirty = false;
  11087. }
  11088. // Stencil func
  11089. if (this._isStencilFuncDirty) {
  11090. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11091. this._isStencilFuncDirty = false;
  11092. }
  11093. // Stencil op
  11094. if (this._isStencilOpDirty) {
  11095. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11096. this._isStencilOpDirty = false;
  11097. }
  11098. };
  11099. return _StencilState;
  11100. }());
  11101. BABYLON._StencilState = _StencilState;
  11102. })(BABYLON || (BABYLON = {}));
  11103. //# sourceMappingURL=babylon.stencilState.js.map
  11104. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11105. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11106. s = arguments[i];
  11107. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11108. t[p] = s[p];
  11109. }
  11110. return t;
  11111. };
  11112. var BABYLON;
  11113. (function (BABYLON) {
  11114. /**
  11115. * Keeps track of all the buffer info used in engine.
  11116. */
  11117. var BufferPointer = /** @class */ (function () {
  11118. function BufferPointer() {
  11119. }
  11120. return BufferPointer;
  11121. }());
  11122. /**
  11123. * Interface for attribute information associated with buffer instanciation
  11124. */
  11125. var InstancingAttributeInfo = /** @class */ (function () {
  11126. function InstancingAttributeInfo() {
  11127. }
  11128. return InstancingAttributeInfo;
  11129. }());
  11130. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11131. /**
  11132. * Define options used to create a render target texture
  11133. */
  11134. var RenderTargetCreationOptions = /** @class */ (function () {
  11135. function RenderTargetCreationOptions() {
  11136. }
  11137. return RenderTargetCreationOptions;
  11138. }());
  11139. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11140. /**
  11141. * Define options used to create a depth texture
  11142. */
  11143. var DepthTextureCreationOptions = /** @class */ (function () {
  11144. function DepthTextureCreationOptions() {
  11145. }
  11146. return DepthTextureCreationOptions;
  11147. }());
  11148. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11149. /**
  11150. * Class used to describe the capabilities of the engine relatively to the current browser
  11151. */
  11152. var EngineCapabilities = /** @class */ (function () {
  11153. function EngineCapabilities() {
  11154. }
  11155. return EngineCapabilities;
  11156. }());
  11157. BABYLON.EngineCapabilities = EngineCapabilities;
  11158. /**
  11159. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11160. */
  11161. var Engine = /** @class */ (function () {
  11162. /**
  11163. * Creates a new engine
  11164. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11165. * @param antialias defines enable antialiasing (default: false)
  11166. * @param options defines further options to be sent to the getContext() function
  11167. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11168. */
  11169. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11170. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11171. var _this = this;
  11172. // Public members
  11173. /**
  11174. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11175. */
  11176. this.forcePOTTextures = false;
  11177. /**
  11178. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11179. */
  11180. this.isFullscreen = false;
  11181. /**
  11182. * Gets a boolean indicating if the pointer is currently locked
  11183. */
  11184. this.isPointerLock = false;
  11185. /**
  11186. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11187. */
  11188. this.cullBackFaces = true;
  11189. /**
  11190. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11191. */
  11192. this.renderEvenInBackground = true;
  11193. /**
  11194. * Gets or sets a boolean indicating that cache can be kept between frames
  11195. */
  11196. this.preventCacheWipeBetweenFrames = false;
  11197. /**
  11198. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11199. **/
  11200. this.enableOfflineSupport = false;
  11201. /**
  11202. * 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)
  11203. **/
  11204. this.disableManifestCheck = false;
  11205. /**
  11206. * Gets the list of created scenes
  11207. */
  11208. this.scenes = new Array();
  11209. /**
  11210. * Gets the list of created postprocesses
  11211. */
  11212. this.postProcesses = new Array();
  11213. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11214. this.validateShaderPrograms = false;
  11215. // Observables
  11216. /**
  11217. * Observable event triggered each time the rendering canvas is resized
  11218. */
  11219. this.onResizeObservable = new BABYLON.Observable();
  11220. /**
  11221. * Observable event triggered each time the canvas loses focus
  11222. */
  11223. this.onCanvasBlurObservable = new BABYLON.Observable();
  11224. /**
  11225. * Observable event triggered each time the canvas gains focus
  11226. */
  11227. this.onCanvasFocusObservable = new BABYLON.Observable();
  11228. /**
  11229. * Observable event triggered each time the canvas receives pointerout event
  11230. */
  11231. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11232. /**
  11233. * Observable event triggered before each texture is initialized
  11234. */
  11235. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11236. //WebVR
  11237. this._vrDisplay = undefined;
  11238. this._vrSupported = false;
  11239. this._vrExclusivePointerMode = false;
  11240. // Uniform buffers list
  11241. /**
  11242. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11243. */
  11244. this.disableUniformBuffers = false;
  11245. /** @hidden */
  11246. this._uniformBuffers = new Array();
  11247. // Observables
  11248. /**
  11249. * Observable raised when the engine begins a new frame
  11250. */
  11251. this.onBeginFrameObservable = new BABYLON.Observable();
  11252. /**
  11253. * Observable raised when the engine ends the current frame
  11254. */
  11255. this.onEndFrameObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable raised when the engine is about to compile a shader
  11258. */
  11259. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable raised when the engine has jsut compiled a shader
  11262. */
  11263. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11264. this._windowIsBackground = false;
  11265. this._webGLVersion = 1.0;
  11266. /** @hidden */
  11267. this._badOS = false;
  11268. /** @hidden */
  11269. this._badDesktopOS = false;
  11270. /**
  11271. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11272. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11273. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11274. */
  11275. this.disableTextureBindingOptimization = false;
  11276. /**
  11277. * Observable signaled when VR display mode changes
  11278. */
  11279. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11280. /**
  11281. * Observable signaled when VR request present is complete
  11282. */
  11283. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11284. /**
  11285. * Observable signaled when VR request present starts
  11286. */
  11287. this.onVRRequestPresentStart = new BABYLON.Observable();
  11288. this._colorWrite = true;
  11289. /** @hidden */
  11290. this._drawCalls = new BABYLON.PerfCounter();
  11291. /** @hidden */
  11292. this._textureCollisions = new BABYLON.PerfCounter();
  11293. this._renderingQueueLaunched = false;
  11294. this._activeRenderLoops = new Array();
  11295. // Deterministic lockstepMaxSteps
  11296. this._deterministicLockstep = false;
  11297. this._lockstepMaxSteps = 4;
  11298. // Lost context
  11299. /**
  11300. * Observable signaled when a context lost event is raised
  11301. */
  11302. this.onContextLostObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable signaled when a context restored event is raised
  11305. */
  11306. this.onContextRestoredObservable = new BABYLON.Observable();
  11307. this._contextWasLost = false;
  11308. this._doNotHandleContextLost = false;
  11309. // FPS
  11310. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11311. this._fps = 60;
  11312. this._deltaTime = 0;
  11313. /**
  11314. * Turn this value on if you want to pause FPS computation when in background
  11315. */
  11316. this.disablePerformanceMonitorInBackground = false;
  11317. // States
  11318. /** @hidden */
  11319. this._depthCullingState = new BABYLON._DepthCullingState();
  11320. /** @hidden */
  11321. this._stencilState = new BABYLON._StencilState();
  11322. /** @hidden */
  11323. this._alphaState = new BABYLON._AlphaState();
  11324. /** @hidden */
  11325. this._alphaMode = Engine.ALPHA_DISABLE;
  11326. // Cache
  11327. this._internalTexturesCache = new Array();
  11328. /** @hidden */
  11329. this._activeChannel = 0;
  11330. this._currentTextureChannel = -1;
  11331. /** @hidden */
  11332. this._boundTexturesCache = {};
  11333. this._compiledEffects = {};
  11334. this._vertexAttribArraysEnabled = [];
  11335. this._uintIndicesCurrentlySet = false;
  11336. this._currentBoundBuffer = new Array();
  11337. /** @hidden */
  11338. this._currentFramebuffer = null;
  11339. this._currentBufferPointers = new Array();
  11340. this._currentInstanceLocations = new Array();
  11341. this._currentInstanceBuffers = new Array();
  11342. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11343. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11344. this._vaoRecordInProgress = false;
  11345. this._mustWipeVertexAttributes = false;
  11346. this._nextFreeTextureSlots = new Array();
  11347. this._maxSimultaneousTextures = 0;
  11348. this._activeRequests = new Array();
  11349. // Hardware supported Compressed Textures
  11350. this._texturesSupported = new Array();
  11351. /**
  11352. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11353. */
  11354. this.premultipliedAlpha = true;
  11355. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11356. this._onVRFullScreenTriggered = function () {
  11357. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11358. //get the old size before we change
  11359. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11360. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11361. //get the width and height, change the render size
  11362. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11363. _this.setHardwareScalingLevel(1);
  11364. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11365. }
  11366. else {
  11367. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11368. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11369. }
  11370. };
  11371. this._unpackFlipYCached = null;
  11372. this._boundUniforms = {};
  11373. // Register promises
  11374. BABYLON.PromisePolyfill.Apply();
  11375. var canvas = null;
  11376. Engine.Instances.push(this);
  11377. if (!canvasOrContext) {
  11378. return;
  11379. }
  11380. options = options || {};
  11381. if (canvasOrContext.getContext) {
  11382. canvas = canvasOrContext;
  11383. this._renderingCanvas = canvas;
  11384. if (antialias != null) {
  11385. options.antialias = antialias;
  11386. }
  11387. if (options.deterministicLockstep === undefined) {
  11388. options.deterministicLockstep = false;
  11389. }
  11390. if (options.lockstepMaxSteps === undefined) {
  11391. options.lockstepMaxSteps = 4;
  11392. }
  11393. if (options.preserveDrawingBuffer === undefined) {
  11394. options.preserveDrawingBuffer = false;
  11395. }
  11396. if (options.audioEngine === undefined) {
  11397. options.audioEngine = true;
  11398. }
  11399. if (options.stencil === undefined) {
  11400. options.stencil = true;
  11401. }
  11402. if (options.premultipliedAlpha === false) {
  11403. this.premultipliedAlpha = false;
  11404. }
  11405. this._deterministicLockstep = options.deterministicLockstep;
  11406. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11407. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11408. // Exceptions
  11409. if (navigator && navigator.userAgent) {
  11410. var ua = navigator.userAgent;
  11411. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11412. var exception = _a[_i];
  11413. var key = exception.key;
  11414. var targets = exception.targets;
  11415. if (ua.indexOf(key) > -1) {
  11416. if (exception.capture && exception.captureConstraint) {
  11417. var capture = exception.capture;
  11418. var constraint = exception.captureConstraint;
  11419. var regex = new RegExp(capture);
  11420. var matches = regex.exec(ua);
  11421. if (matches && matches.length > 0) {
  11422. var capturedValue = parseInt(matches[matches.length - 1]);
  11423. if (capturedValue >= constraint) {
  11424. continue;
  11425. }
  11426. }
  11427. }
  11428. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11429. var target = targets_1[_b];
  11430. switch (target) {
  11431. case "uniformBuffer":
  11432. this.disableUniformBuffers = true;
  11433. break;
  11434. case "textureBindingOptimization":
  11435. this.disableTextureBindingOptimization = true;
  11436. break;
  11437. }
  11438. }
  11439. }
  11440. }
  11441. }
  11442. // GL
  11443. if (!options.disableWebGL2Support) {
  11444. try {
  11445. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11446. if (this._gl) {
  11447. this._webGLVersion = 2.0;
  11448. }
  11449. }
  11450. catch (e) {
  11451. // Do nothing
  11452. }
  11453. }
  11454. if (!this._gl) {
  11455. if (!canvas) {
  11456. throw new Error("The provided canvas is null or undefined.");
  11457. }
  11458. try {
  11459. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11460. }
  11461. catch (e) {
  11462. throw new Error("WebGL not supported");
  11463. }
  11464. }
  11465. if (!this._gl) {
  11466. throw new Error("WebGL not supported");
  11467. }
  11468. this._onCanvasFocus = function () {
  11469. _this.onCanvasFocusObservable.notifyObservers(_this);
  11470. };
  11471. this._onCanvasBlur = function () {
  11472. _this.onCanvasBlurObservable.notifyObservers(_this);
  11473. };
  11474. canvas.addEventListener("focus", this._onCanvasFocus);
  11475. canvas.addEventListener("blur", this._onCanvasBlur);
  11476. this._onBlur = function () {
  11477. if (_this.disablePerformanceMonitorInBackground) {
  11478. _this._performanceMonitor.disable();
  11479. }
  11480. _this._windowIsBackground = true;
  11481. };
  11482. this._onFocus = function () {
  11483. if (_this.disablePerformanceMonitorInBackground) {
  11484. _this._performanceMonitor.enable();
  11485. }
  11486. _this._windowIsBackground = false;
  11487. };
  11488. this._onCanvasPointerOut = function (ev) {
  11489. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11490. };
  11491. window.addEventListener("blur", this._onBlur);
  11492. window.addEventListener("focus", this._onFocus);
  11493. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11494. // Context lost
  11495. if (!this._doNotHandleContextLost) {
  11496. this._onContextLost = function (evt) {
  11497. evt.preventDefault();
  11498. _this._contextWasLost = true;
  11499. BABYLON.Tools.Warn("WebGL context lost.");
  11500. _this.onContextLostObservable.notifyObservers(_this);
  11501. };
  11502. this._onContextRestored = function (evt) {
  11503. // Adding a timeout to avoid race condition at browser level
  11504. setTimeout(function () {
  11505. // Rebuild gl context
  11506. _this._initGLContext();
  11507. // Rebuild effects
  11508. _this._rebuildEffects();
  11509. // Rebuild textures
  11510. _this._rebuildInternalTextures();
  11511. // Rebuild buffers
  11512. _this._rebuildBuffers();
  11513. // Cache
  11514. _this.wipeCaches(true);
  11515. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11516. _this.onContextRestoredObservable.notifyObservers(_this);
  11517. _this._contextWasLost = false;
  11518. }, 0);
  11519. };
  11520. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11521. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11522. }
  11523. }
  11524. else {
  11525. this._gl = canvasOrContext;
  11526. this._renderingCanvas = this._gl.canvas;
  11527. if (this._gl.renderbufferStorageMultisample) {
  11528. this._webGLVersion = 2.0;
  11529. }
  11530. options.stencil = this._gl.getContextAttributes().stencil;
  11531. }
  11532. // Viewport
  11533. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11534. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11535. this.resize();
  11536. this._isStencilEnable = options.stencil ? true : false;
  11537. this._initGLContext();
  11538. if (canvas) {
  11539. // Fullscreen
  11540. this._onFullscreenChange = function () {
  11541. if (document.fullscreen !== undefined) {
  11542. _this.isFullscreen = document.fullscreen;
  11543. }
  11544. else if (document.mozFullScreen !== undefined) {
  11545. _this.isFullscreen = document.mozFullScreen;
  11546. }
  11547. else if (document.webkitIsFullScreen !== undefined) {
  11548. _this.isFullscreen = document.webkitIsFullScreen;
  11549. }
  11550. else if (document.msIsFullScreen !== undefined) {
  11551. _this.isFullscreen = document.msIsFullScreen;
  11552. }
  11553. // Pointer lock
  11554. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11555. canvas.requestPointerLock = canvas.requestPointerLock ||
  11556. canvas.msRequestPointerLock ||
  11557. canvas.mozRequestPointerLock ||
  11558. canvas.webkitRequestPointerLock;
  11559. if (canvas.requestPointerLock) {
  11560. canvas.requestPointerLock();
  11561. }
  11562. }
  11563. };
  11564. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11565. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11566. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11567. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11568. // Pointer lock
  11569. this._onPointerLockChange = function () {
  11570. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11571. document.webkitPointerLockElement === canvas ||
  11572. document.msPointerLockElement === canvas ||
  11573. document.pointerLockElement === canvas);
  11574. };
  11575. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11576. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11577. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11578. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11579. this._onVRDisplayPointerRestricted = function () {
  11580. if (canvas) {
  11581. canvas.requestPointerLock();
  11582. }
  11583. };
  11584. this._onVRDisplayPointerUnrestricted = function () {
  11585. document.exitPointerLock();
  11586. };
  11587. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11588. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11589. }
  11590. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11591. Engine.audioEngine = new BABYLON.AudioEngine();
  11592. }
  11593. // Prepare buffer pointers
  11594. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11595. this._currentBufferPointers[i] = new BufferPointer();
  11596. }
  11597. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11598. // Load WebVR Devices
  11599. if (options.autoEnableWebVR) {
  11600. this.initWebVR();
  11601. }
  11602. // Detect if we are running on a faulty buggy OS.
  11603. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11604. // Detect if we are running on a faulty buggy desktop OS.
  11605. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11606. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11607. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11608. }
  11609. Object.defineProperty(Engine, "LastCreatedEngine", {
  11610. /**
  11611. * Gets the latest created engine
  11612. */
  11613. get: function () {
  11614. if (Engine.Instances.length === 0) {
  11615. return null;
  11616. }
  11617. return Engine.Instances[Engine.Instances.length - 1];
  11618. },
  11619. enumerable: true,
  11620. configurable: true
  11621. });
  11622. Object.defineProperty(Engine, "LastCreatedScene", {
  11623. /**
  11624. * Gets the latest created scene
  11625. */
  11626. get: function () {
  11627. var lastCreatedEngine = Engine.LastCreatedEngine;
  11628. if (!lastCreatedEngine) {
  11629. return null;
  11630. }
  11631. if (lastCreatedEngine.scenes.length === 0) {
  11632. return null;
  11633. }
  11634. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11635. },
  11636. enumerable: true,
  11637. configurable: true
  11638. });
  11639. /**
  11640. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11641. * @param flag defines which part of the materials must be marked as dirty
  11642. * @param predicate defines a predicate used to filter which materials should be affected
  11643. */
  11644. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11645. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11646. var engine = Engine.Instances[engineIndex];
  11647. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11648. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11649. }
  11650. }
  11651. };
  11652. Object.defineProperty(Engine, "Version", {
  11653. /**
  11654. * Returns the current version of the framework
  11655. */
  11656. get: function () {
  11657. return "3.3.0-alpha.12";
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11663. /**
  11664. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11665. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11666. */
  11667. get: function () {
  11668. return this._vrExclusivePointerMode;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11674. /**
  11675. * Gets a boolean indicating that the engine supports uniform buffers
  11676. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11677. */
  11678. get: function () {
  11679. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11685. /**
  11686. * Gets a boolean indicating that only power of 2 textures are supported
  11687. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11688. */
  11689. get: function () {
  11690. return this._webGLVersion < 2 || this.forcePOTTextures;
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11696. /**
  11697. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11698. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11699. */
  11700. get: function () {
  11701. return this._doNotHandleContextLost;
  11702. },
  11703. set: function (value) {
  11704. this._doNotHandleContextLost = value;
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11710. /**
  11711. * Gets the performance monitor attached to this engine
  11712. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11713. */
  11714. get: function () {
  11715. return this._performanceMonitor;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11721. /**
  11722. * Gets the list of texture formats supported
  11723. */
  11724. get: function () {
  11725. return this._texturesSupported;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11731. /**
  11732. * Gets the list of texture formats in use
  11733. */
  11734. get: function () {
  11735. return this._textureFormatInUse;
  11736. },
  11737. enumerable: true,
  11738. configurable: true
  11739. });
  11740. Object.defineProperty(Engine.prototype, "currentViewport", {
  11741. /**
  11742. * Gets the current viewport
  11743. */
  11744. get: function () {
  11745. return this._cachedViewport;
  11746. },
  11747. enumerable: true,
  11748. configurable: true
  11749. });
  11750. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11751. /**
  11752. * Gets the default empty texture
  11753. */
  11754. get: function () {
  11755. if (!this._emptyTexture) {
  11756. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11757. }
  11758. return this._emptyTexture;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11764. /**
  11765. * Gets the default empty 3D texture
  11766. */
  11767. get: function () {
  11768. if (!this._emptyTexture3D) {
  11769. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11770. }
  11771. return this._emptyTexture3D;
  11772. },
  11773. enumerable: true,
  11774. configurable: true
  11775. });
  11776. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11777. /**
  11778. * Gets the default empty cube texture
  11779. */
  11780. get: function () {
  11781. if (!this._emptyCubeTexture) {
  11782. var faceData = new Uint8Array(4);
  11783. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11784. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11785. }
  11786. return this._emptyCubeTexture;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Engine.prototype._rebuildInternalTextures = function () {
  11792. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11793. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11794. var internalTexture = currentState_1[_i];
  11795. internalTexture._rebuild();
  11796. }
  11797. };
  11798. Engine.prototype._rebuildEffects = function () {
  11799. for (var key in this._compiledEffects) {
  11800. var effect = this._compiledEffects[key];
  11801. effect._prepareEffect();
  11802. }
  11803. BABYLON.Effect.ResetCache();
  11804. };
  11805. Engine.prototype._rebuildBuffers = function () {
  11806. // Index / Vertex
  11807. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11808. var scene = _a[_i];
  11809. scene.resetCachedMaterial();
  11810. scene._rebuildGeometries();
  11811. scene._rebuildTextures();
  11812. }
  11813. // Uniforms
  11814. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11815. var uniformBuffer = _c[_b];
  11816. uniformBuffer._rebuild();
  11817. }
  11818. };
  11819. Engine.prototype._initGLContext = function () {
  11820. // Caps
  11821. this._caps = new EngineCapabilities();
  11822. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11823. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11824. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11825. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11826. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11827. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11828. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11829. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11830. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11831. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11832. // Infos
  11833. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11834. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11835. if (rendererInfo != null) {
  11836. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11837. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11838. }
  11839. if (!this._glVendor) {
  11840. this._glVendor = "Unknown vendor";
  11841. }
  11842. if (!this._glRenderer) {
  11843. this._glRenderer = "Unknown renderer";
  11844. }
  11845. // Constants
  11846. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11847. if (this._gl.RGBA16F !== 0x881A) {
  11848. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11849. }
  11850. if (this._gl.RGBA32F !== 0x8814) {
  11851. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11852. }
  11853. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11854. this._gl.DEPTH24_STENCIL8 = 35056;
  11855. }
  11856. // Extensions
  11857. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11858. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11859. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11860. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11861. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11862. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11863. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11864. 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');
  11865. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11866. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11867. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11868. this._caps.highPrecisionShaderSupported = true;
  11869. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11870. if (this._caps.timerQuery) {
  11871. if (this._webGLVersion === 1) {
  11872. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11873. }
  11874. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11875. }
  11876. // Checks if some of the format renders first to allow the use of webgl inspector.
  11877. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11878. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11879. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11880. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11881. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11882. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11883. if (this._webGLVersion > 1) {
  11884. this._gl.HALF_FLOAT_OES = 0x140B;
  11885. }
  11886. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11887. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11888. // Draw buffers
  11889. if (this._webGLVersion > 1) {
  11890. this._caps.drawBuffersExtension = true;
  11891. }
  11892. else {
  11893. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11894. if (drawBuffersExtension !== null) {
  11895. this._caps.drawBuffersExtension = true;
  11896. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11897. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11898. for (var i = 0; i < 16; i++) {
  11899. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11900. }
  11901. }
  11902. else {
  11903. this._caps.drawBuffersExtension = false;
  11904. }
  11905. }
  11906. // Depth Texture
  11907. if (this._webGLVersion > 1) {
  11908. this._caps.depthTextureExtension = true;
  11909. }
  11910. else {
  11911. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11912. if (depthTextureExtension != null) {
  11913. this._caps.depthTextureExtension = true;
  11914. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11915. }
  11916. }
  11917. // Vertex array object
  11918. if (this._webGLVersion > 1) {
  11919. this._caps.vertexArrayObject = true;
  11920. }
  11921. else {
  11922. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11923. if (vertexArrayObjectExtension != null) {
  11924. this._caps.vertexArrayObject = true;
  11925. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11926. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11927. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11928. }
  11929. else {
  11930. this._caps.vertexArrayObject = false;
  11931. }
  11932. }
  11933. // Instances count
  11934. if (this._webGLVersion > 1) {
  11935. this._caps.instancedArrays = true;
  11936. }
  11937. else {
  11938. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11939. if (instanceExtension != null) {
  11940. this._caps.instancedArrays = true;
  11941. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11942. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11943. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11944. }
  11945. else {
  11946. this._caps.instancedArrays = false;
  11947. }
  11948. }
  11949. // Intelligently add supported compressed formats in order to check for.
  11950. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11951. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11952. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11953. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11954. if (this._caps.astc)
  11955. this.texturesSupported.push('-astc.ktx');
  11956. if (this._caps.s3tc)
  11957. this.texturesSupported.push('-dxt.ktx');
  11958. if (this._caps.pvrtc)
  11959. this.texturesSupported.push('-pvrtc.ktx');
  11960. if (this._caps.etc2)
  11961. this.texturesSupported.push('-etc2.ktx');
  11962. if (this._caps.etc1)
  11963. this.texturesSupported.push('-etc1.ktx');
  11964. if (this._gl.getShaderPrecisionFormat) {
  11965. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11966. if (highp) {
  11967. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11968. }
  11969. }
  11970. // Depth buffer
  11971. this.setDepthBuffer(true);
  11972. this.setDepthFunctionToLessOrEqual();
  11973. this.setDepthWrite(true);
  11974. // Texture maps
  11975. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11976. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11977. this._nextFreeTextureSlots.push(slot);
  11978. }
  11979. };
  11980. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11981. /**
  11982. * Gets version of the current webGL context
  11983. */
  11984. get: function () {
  11985. return this._webGLVersion;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11991. /**
  11992. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11993. */
  11994. get: function () {
  11995. return this._isStencilEnable;
  11996. },
  11997. enumerable: true,
  11998. configurable: true
  11999. });
  12000. Engine.prototype._prepareWorkingCanvas = function () {
  12001. if (this._workingCanvas) {
  12002. return;
  12003. }
  12004. this._workingCanvas = document.createElement("canvas");
  12005. var context = this._workingCanvas.getContext("2d");
  12006. if (context) {
  12007. this._workingContext = context;
  12008. }
  12009. };
  12010. /**
  12011. * Reset the texture cache to empty state
  12012. */
  12013. Engine.prototype.resetTextureCache = function () {
  12014. for (var key in this._boundTexturesCache) {
  12015. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12016. continue;
  12017. }
  12018. var boundTexture = this._boundTexturesCache[key];
  12019. if (boundTexture) {
  12020. this._removeDesignatedSlot(boundTexture);
  12021. }
  12022. this._boundTexturesCache[key] = null;
  12023. }
  12024. if (!this.disableTextureBindingOptimization) {
  12025. this._nextFreeTextureSlots = [];
  12026. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12027. this._nextFreeTextureSlots.push(slot);
  12028. }
  12029. }
  12030. this._currentTextureChannel = -1;
  12031. };
  12032. /**
  12033. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12034. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12035. * @returns true if engine is in deterministic lock step mode
  12036. */
  12037. Engine.prototype.isDeterministicLockStep = function () {
  12038. return this._deterministicLockstep;
  12039. };
  12040. /**
  12041. * Gets the max steps when engine is running in deterministic lock step
  12042. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12043. * @returns the max steps
  12044. */
  12045. Engine.prototype.getLockstepMaxSteps = function () {
  12046. return this._lockstepMaxSteps;
  12047. };
  12048. /**
  12049. * Gets an object containing information about the current webGL context
  12050. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12051. */
  12052. Engine.prototype.getGlInfo = function () {
  12053. return {
  12054. vendor: this._glVendor,
  12055. renderer: this._glRenderer,
  12056. version: this._glVersion
  12057. };
  12058. };
  12059. /**
  12060. * Gets current aspect ratio
  12061. * @param camera defines the camera to use to get the aspect ratio
  12062. * @param useScreen defines if screen size must be used (or the current render target if any)
  12063. * @returns a number defining the aspect ratio
  12064. */
  12065. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12066. if (useScreen === void 0) { useScreen = false; }
  12067. var viewport = camera.viewport;
  12068. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12069. };
  12070. /**
  12071. * Gets current screen aspect ratio
  12072. * @returns a number defining the aspect ratio
  12073. */
  12074. Engine.prototype.getScreenAspectRatio = function () {
  12075. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12076. };
  12077. /**
  12078. * Gets the current render width
  12079. * @param useScreen defines if screen size must be used (or the current render target if any)
  12080. * @returns a number defining the current render width
  12081. */
  12082. Engine.prototype.getRenderWidth = function (useScreen) {
  12083. if (useScreen === void 0) { useScreen = false; }
  12084. if (!useScreen && this._currentRenderTarget) {
  12085. return this._currentRenderTarget.width;
  12086. }
  12087. return this._gl.drawingBufferWidth;
  12088. };
  12089. /**
  12090. * Gets the current render height
  12091. * @param useScreen defines if screen size must be used (or the current render target if any)
  12092. * @returns a number defining the current render height
  12093. */
  12094. Engine.prototype.getRenderHeight = function (useScreen) {
  12095. if (useScreen === void 0) { useScreen = false; }
  12096. if (!useScreen && this._currentRenderTarget) {
  12097. return this._currentRenderTarget.height;
  12098. }
  12099. return this._gl.drawingBufferHeight;
  12100. };
  12101. /**
  12102. * Gets the HTML canvas attached with the current webGL context
  12103. * @returns a HTML canvas
  12104. */
  12105. Engine.prototype.getRenderingCanvas = function () {
  12106. return this._renderingCanvas;
  12107. };
  12108. /**
  12109. * Gets the client rect of the HTML canvas attached with the current webGL context
  12110. * @returns a client rectanglee
  12111. */
  12112. Engine.prototype.getRenderingCanvasClientRect = function () {
  12113. if (!this._renderingCanvas) {
  12114. return null;
  12115. }
  12116. return this._renderingCanvas.getBoundingClientRect();
  12117. };
  12118. /**
  12119. * Defines the hardware scaling level.
  12120. * By default the hardware scaling level is computed from the window device ratio.
  12121. * 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.
  12122. * @param level defines the level to use
  12123. */
  12124. Engine.prototype.setHardwareScalingLevel = function (level) {
  12125. this._hardwareScalingLevel = level;
  12126. this.resize();
  12127. };
  12128. /**
  12129. * Gets the current hardware scaling level.
  12130. * By default the hardware scaling level is computed from the window device ratio.
  12131. * 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.
  12132. * @returns a number indicating the current hardware scaling level
  12133. */
  12134. Engine.prototype.getHardwareScalingLevel = function () {
  12135. return this._hardwareScalingLevel;
  12136. };
  12137. /**
  12138. * Gets the list of loaded textures
  12139. * @returns an array containing all loaded textures
  12140. */
  12141. Engine.prototype.getLoadedTexturesCache = function () {
  12142. return this._internalTexturesCache;
  12143. };
  12144. /**
  12145. * Gets the object containing all engine capabilities
  12146. * @returns the EngineCapabilities object
  12147. */
  12148. Engine.prototype.getCaps = function () {
  12149. return this._caps;
  12150. };
  12151. Object.defineProperty(Engine.prototype, "drawCalls", {
  12152. /** @hidden */
  12153. get: function () {
  12154. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12155. return 0;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12161. /** @hidden */
  12162. get: function () {
  12163. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12164. return null;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. /**
  12170. * Gets the current depth function
  12171. * @returns a number defining the depth function
  12172. */
  12173. Engine.prototype.getDepthFunction = function () {
  12174. return this._depthCullingState.depthFunc;
  12175. };
  12176. /**
  12177. * Sets the current depth function
  12178. * @param depthFunc defines the function to use
  12179. */
  12180. Engine.prototype.setDepthFunction = function (depthFunc) {
  12181. this._depthCullingState.depthFunc = depthFunc;
  12182. };
  12183. /**
  12184. * Sets the current depth function to GREATER
  12185. */
  12186. Engine.prototype.setDepthFunctionToGreater = function () {
  12187. this._depthCullingState.depthFunc = this._gl.GREATER;
  12188. };
  12189. /**
  12190. * Sets the current depth function to GEQUAL
  12191. */
  12192. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12193. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12194. };
  12195. /**
  12196. * Sets the current depth function to LESS
  12197. */
  12198. Engine.prototype.setDepthFunctionToLess = function () {
  12199. this._depthCullingState.depthFunc = this._gl.LESS;
  12200. };
  12201. /**
  12202. * Sets the current depth function to LEQUAL
  12203. */
  12204. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12205. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12206. };
  12207. /**
  12208. * Gets a boolean indicating if stencil buffer is enabled
  12209. * @returns the current stencil buffer state
  12210. */
  12211. Engine.prototype.getStencilBuffer = function () {
  12212. return this._stencilState.stencilTest;
  12213. };
  12214. /**
  12215. * Enable or disable the stencil buffer
  12216. * @param enable defines if the stencil buffer must be enabled or disabled
  12217. */
  12218. Engine.prototype.setStencilBuffer = function (enable) {
  12219. this._stencilState.stencilTest = enable;
  12220. };
  12221. /**
  12222. * Gets the current stencil mask
  12223. * @returns a number defining the new stencil mask to use
  12224. */
  12225. Engine.prototype.getStencilMask = function () {
  12226. return this._stencilState.stencilMask;
  12227. };
  12228. /**
  12229. * Sets the current stencil mask
  12230. * @param mask defines the new stencil mask to use
  12231. */
  12232. Engine.prototype.setStencilMask = function (mask) {
  12233. this._stencilState.stencilMask = mask;
  12234. };
  12235. /**
  12236. * Gets the current stencil function
  12237. * @returns a number defining the stencil function to use
  12238. */
  12239. Engine.prototype.getStencilFunction = function () {
  12240. return this._stencilState.stencilFunc;
  12241. };
  12242. /**
  12243. * Gets the current stencil reference value
  12244. * @returns a number defining the stencil reference value to use
  12245. */
  12246. Engine.prototype.getStencilFunctionReference = function () {
  12247. return this._stencilState.stencilFuncRef;
  12248. };
  12249. /**
  12250. * Gets the current stencil mask
  12251. * @returns a number defining the stencil mask to use
  12252. */
  12253. Engine.prototype.getStencilFunctionMask = function () {
  12254. return this._stencilState.stencilFuncMask;
  12255. };
  12256. /**
  12257. * Sets the current stencil function
  12258. * @param stencilFunc defines the new stencil function to use
  12259. */
  12260. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12261. this._stencilState.stencilFunc = stencilFunc;
  12262. };
  12263. /**
  12264. * Sets the current stencil reference
  12265. * @param reference defines the new stencil reference to use
  12266. */
  12267. Engine.prototype.setStencilFunctionReference = function (reference) {
  12268. this._stencilState.stencilFuncRef = reference;
  12269. };
  12270. /**
  12271. * Sets the current stencil mask
  12272. * @param mask defines the new stencil mask to use
  12273. */
  12274. Engine.prototype.setStencilFunctionMask = function (mask) {
  12275. this._stencilState.stencilFuncMask = mask;
  12276. };
  12277. /**
  12278. * Gets the current stencil operation when stencil fails
  12279. * @returns a number defining stencil operation to use when stencil fails
  12280. */
  12281. Engine.prototype.getStencilOperationFail = function () {
  12282. return this._stencilState.stencilOpStencilFail;
  12283. };
  12284. /**
  12285. * Gets the current stencil operation when depth fails
  12286. * @returns a number defining stencil operation to use when depth fails
  12287. */
  12288. Engine.prototype.getStencilOperationDepthFail = function () {
  12289. return this._stencilState.stencilOpDepthFail;
  12290. };
  12291. /**
  12292. * Gets the current stencil operation when stencil passes
  12293. * @returns a number defining stencil operation to use when stencil passes
  12294. */
  12295. Engine.prototype.getStencilOperationPass = function () {
  12296. return this._stencilState.stencilOpStencilDepthPass;
  12297. };
  12298. /**
  12299. * Sets the stencil operation to use when stencil fails
  12300. * @param operation defines the stencil operation to use when stencil fails
  12301. */
  12302. Engine.prototype.setStencilOperationFail = function (operation) {
  12303. this._stencilState.stencilOpStencilFail = operation;
  12304. };
  12305. /**
  12306. * Sets the stencil operation to use when depth fails
  12307. * @param operation defines the stencil operation to use when depth fails
  12308. */
  12309. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12310. this._stencilState.stencilOpDepthFail = operation;
  12311. };
  12312. /**
  12313. * Sets the stencil operation to use when stencil passes
  12314. * @param operation defines the stencil operation to use when stencil passes
  12315. */
  12316. Engine.prototype.setStencilOperationPass = function (operation) {
  12317. this._stencilState.stencilOpStencilDepthPass = operation;
  12318. };
  12319. /**
  12320. * Sets a boolean indicating if the dithering state is enabled or disabled
  12321. * @param value defines the dithering state
  12322. */
  12323. Engine.prototype.setDitheringState = function (value) {
  12324. if (value) {
  12325. this._gl.enable(this._gl.DITHER);
  12326. }
  12327. else {
  12328. this._gl.disable(this._gl.DITHER);
  12329. }
  12330. };
  12331. /**
  12332. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12333. * @param value defines the rasterizer state
  12334. */
  12335. Engine.prototype.setRasterizerState = function (value) {
  12336. if (value) {
  12337. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12338. }
  12339. else {
  12340. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12341. }
  12342. };
  12343. /**
  12344. * stop executing a render loop function and remove it from the execution array
  12345. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12346. */
  12347. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12348. if (!renderFunction) {
  12349. this._activeRenderLoops = [];
  12350. return;
  12351. }
  12352. var index = this._activeRenderLoops.indexOf(renderFunction);
  12353. if (index >= 0) {
  12354. this._activeRenderLoops.splice(index, 1);
  12355. }
  12356. };
  12357. /** @hidden */
  12358. Engine.prototype._renderLoop = function () {
  12359. if (!this._contextWasLost) {
  12360. var shouldRender = true;
  12361. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12362. shouldRender = false;
  12363. }
  12364. if (shouldRender) {
  12365. // Start new frame
  12366. this.beginFrame();
  12367. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12368. var renderFunction = this._activeRenderLoops[index];
  12369. renderFunction();
  12370. }
  12371. // Present
  12372. this.endFrame();
  12373. }
  12374. }
  12375. if (this._activeRenderLoops.length > 0) {
  12376. // Register new frame
  12377. var requester = null;
  12378. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12379. requester = this._vrDisplay;
  12380. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12381. }
  12382. else {
  12383. this._renderingQueueLaunched = false;
  12384. }
  12385. };
  12386. /**
  12387. * Register and execute a render loop. The engine can have more than one render function
  12388. * @param renderFunction defines the function to continuously execute
  12389. */
  12390. Engine.prototype.runRenderLoop = function (renderFunction) {
  12391. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12392. return;
  12393. }
  12394. this._activeRenderLoops.push(renderFunction);
  12395. if (!this._renderingQueueLaunched) {
  12396. this._renderingQueueLaunched = true;
  12397. this._bindedRenderFunction = this._renderLoop.bind(this);
  12398. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12399. }
  12400. };
  12401. /**
  12402. * Toggle full screen mode
  12403. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12404. * @param options defines an option object to be sent to the requestFullscreen function
  12405. */
  12406. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12407. if (this.isFullscreen) {
  12408. BABYLON.Tools.ExitFullscreen();
  12409. }
  12410. else {
  12411. this._pointerLockRequested = requestPointerLock;
  12412. if (this._renderingCanvas) {
  12413. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12414. }
  12415. }
  12416. };
  12417. /**
  12418. * Clear the current render buffer or the current render target (if any is set up)
  12419. * @param color defines the color to use
  12420. * @param backBuffer defines if the back buffer must be cleared
  12421. * @param depth defines if the depth buffer must be cleared
  12422. * @param stencil defines if the stencil buffer must be cleared
  12423. */
  12424. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12425. if (stencil === void 0) { stencil = false; }
  12426. this.applyStates();
  12427. var mode = 0;
  12428. if (backBuffer && color) {
  12429. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12430. mode |= this._gl.COLOR_BUFFER_BIT;
  12431. }
  12432. if (depth) {
  12433. this._gl.clearDepth(1.0);
  12434. mode |= this._gl.DEPTH_BUFFER_BIT;
  12435. }
  12436. if (stencil) {
  12437. this._gl.clearStencil(0);
  12438. mode |= this._gl.STENCIL_BUFFER_BIT;
  12439. }
  12440. this._gl.clear(mode);
  12441. };
  12442. /**
  12443. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12444. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12445. * @param y defines the y-coordinate of the corner of the clear rectangle
  12446. * @param width defines the width of the clear rectangle
  12447. * @param height defines the height of the clear rectangle
  12448. * @param clearColor defines the clear color
  12449. */
  12450. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12451. var gl = this._gl;
  12452. // Save state
  12453. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12454. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12455. // Change state
  12456. gl.enable(gl.SCISSOR_TEST);
  12457. gl.scissor(x, y, width, height);
  12458. // Clear
  12459. this.clear(clearColor, true, true, true);
  12460. // Restore state
  12461. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12462. if (curScissor === true) {
  12463. gl.enable(gl.SCISSOR_TEST);
  12464. }
  12465. else {
  12466. gl.disable(gl.SCISSOR_TEST);
  12467. }
  12468. };
  12469. /** @hidden */
  12470. Engine.prototype._viewport = function (x, y, width, height) {
  12471. if (x !== this._viewportCached.x ||
  12472. y !== this._viewportCached.y ||
  12473. width !== this._viewportCached.z ||
  12474. height !== this._viewportCached.w) {
  12475. this._viewportCached.x = x;
  12476. this._viewportCached.y = y;
  12477. this._viewportCached.z = width;
  12478. this._viewportCached.w = height;
  12479. this._gl.viewport(x, y, width, height);
  12480. }
  12481. };
  12482. /**
  12483. * Set the WebGL's viewport
  12484. * @param viewport defines the viewport element to be used
  12485. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12486. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12487. */
  12488. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12489. var width = requiredWidth || this.getRenderWidth();
  12490. var height = requiredHeight || this.getRenderHeight();
  12491. var x = viewport.x || 0;
  12492. var y = viewport.y || 0;
  12493. this._cachedViewport = viewport;
  12494. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12495. };
  12496. /**
  12497. * Directly set the WebGL Viewport
  12498. * @param x defines the x coordinate of the viewport (in screen space)
  12499. * @param y defines the y coordinate of the viewport (in screen space)
  12500. * @param width defines the width of the viewport (in screen space)
  12501. * @param height defines the height of the viewport (in screen space)
  12502. * @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
  12503. */
  12504. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12505. var currentViewport = this._cachedViewport;
  12506. this._cachedViewport = null;
  12507. this._viewport(x, y, width, height);
  12508. return currentViewport;
  12509. };
  12510. /**
  12511. * Begin a new frame
  12512. */
  12513. Engine.prototype.beginFrame = function () {
  12514. this.onBeginFrameObservable.notifyObservers(this);
  12515. this._measureFps();
  12516. };
  12517. /**
  12518. * Enf the current frame
  12519. */
  12520. Engine.prototype.endFrame = function () {
  12521. // Force a flush in case we are using a bad OS.
  12522. if (this._badOS) {
  12523. this.flushFramebuffer();
  12524. }
  12525. // Submit frame to the vr device, if enabled
  12526. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12527. // TODO: We should only submit the frame if we read frameData successfully.
  12528. this._vrDisplay.submitFrame();
  12529. }
  12530. this.onEndFrameObservable.notifyObservers(this);
  12531. };
  12532. /**
  12533. * Resize the view according to the canvas' size
  12534. */
  12535. Engine.prototype.resize = function () {
  12536. // We're not resizing the size of the canvas while in VR mode & presenting
  12537. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12538. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12539. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12540. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12541. }
  12542. };
  12543. /**
  12544. * Force a specific size of the canvas
  12545. * @param width defines the new canvas' width
  12546. * @param height defines the new canvas' height
  12547. */
  12548. Engine.prototype.setSize = function (width, height) {
  12549. if (!this._renderingCanvas) {
  12550. return;
  12551. }
  12552. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12553. return;
  12554. }
  12555. this._renderingCanvas.width = width;
  12556. this._renderingCanvas.height = height;
  12557. for (var index = 0; index < this.scenes.length; index++) {
  12558. var scene = this.scenes[index];
  12559. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12560. var cam = scene.cameras[camIndex];
  12561. cam._currentRenderId = 0;
  12562. }
  12563. }
  12564. if (this.onResizeObservable.hasObservers) {
  12565. this.onResizeObservable.notifyObservers(this);
  12566. }
  12567. };
  12568. // WebVR functions
  12569. /**
  12570. * Gets a boolean indicating if a webVR device was detected
  12571. * @returns true if a webVR device was detected
  12572. */
  12573. Engine.prototype.isVRDevicePresent = function () {
  12574. return !!this._vrDisplay;
  12575. };
  12576. /**
  12577. * Gets the current webVR device
  12578. * @returns the current webVR device (or null)
  12579. */
  12580. Engine.prototype.getVRDevice = function () {
  12581. return this._vrDisplay;
  12582. };
  12583. /**
  12584. * Initializes a webVR display and starts listening to display change events
  12585. * The onVRDisplayChangedObservable will be notified upon these changes
  12586. * @returns The onVRDisplayChangedObservable
  12587. */
  12588. Engine.prototype.initWebVR = function () {
  12589. this.initWebVRAsync();
  12590. return this.onVRDisplayChangedObservable;
  12591. };
  12592. /**
  12593. * Initializes a webVR display and starts listening to display change events
  12594. * The onVRDisplayChangedObservable will be notified upon these changes
  12595. * @returns A promise containing a VRDisplay and if vr is supported
  12596. */
  12597. Engine.prototype.initWebVRAsync = function () {
  12598. var _this = this;
  12599. var notifyObservers = function () {
  12600. var eventArgs = {
  12601. vrDisplay: _this._vrDisplay,
  12602. vrSupported: _this._vrSupported
  12603. };
  12604. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12605. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12606. };
  12607. if (!this._onVrDisplayConnect) {
  12608. this._onVrDisplayConnect = function (event) {
  12609. _this._vrDisplay = event.display;
  12610. notifyObservers();
  12611. };
  12612. this._onVrDisplayDisconnect = function () {
  12613. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12614. _this._vrDisplay = undefined;
  12615. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12616. notifyObservers();
  12617. };
  12618. this._onVrDisplayPresentChange = function () {
  12619. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12620. };
  12621. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12622. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12623. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12624. }
  12625. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12626. this._webVRInitPromise.then(notifyObservers);
  12627. return this._webVRInitPromise;
  12628. };
  12629. /**
  12630. * Call this function to switch to webVR mode
  12631. * Will do nothing if webVR is not supported or if there is no webVR device
  12632. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12633. */
  12634. Engine.prototype.enableVR = function () {
  12635. var _this = this;
  12636. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12637. var onResolved = function () {
  12638. _this.onVRRequestPresentComplete.notifyObservers(true);
  12639. _this._onVRFullScreenTriggered();
  12640. };
  12641. var onRejected = function () {
  12642. _this.onVRRequestPresentComplete.notifyObservers(false);
  12643. };
  12644. this.onVRRequestPresentStart.notifyObservers(this);
  12645. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12646. }
  12647. };
  12648. /**
  12649. * Call this function to leave webVR mode
  12650. * Will do nothing if webVR is not supported or if there is no webVR device
  12651. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12652. */
  12653. Engine.prototype.disableVR = function () {
  12654. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12655. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12656. }
  12657. };
  12658. Engine.prototype._getVRDisplaysAsync = function () {
  12659. var _this = this;
  12660. return new Promise(function (res, rej) {
  12661. if (navigator.getVRDisplays) {
  12662. navigator.getVRDisplays().then(function (devices) {
  12663. _this._vrSupported = true;
  12664. // note that devices may actually be an empty array. This is fine;
  12665. // we expect this._vrDisplay to be undefined in this case.
  12666. _this._vrDisplay = devices[0];
  12667. res({
  12668. vrDisplay: _this._vrDisplay,
  12669. vrSupported: _this._vrSupported
  12670. });
  12671. });
  12672. }
  12673. else {
  12674. _this._vrDisplay = undefined;
  12675. _this._vrSupported = false;
  12676. res({
  12677. vrDisplay: _this._vrDisplay,
  12678. vrSupported: _this._vrSupported
  12679. });
  12680. }
  12681. });
  12682. };
  12683. /**
  12684. * Binds the frame buffer to the specified texture.
  12685. * @param texture The texture to render to or null for the default canvas
  12686. * @param faceIndex The face of the texture to render to in case of cube texture
  12687. * @param requiredWidth The width of the target to render to
  12688. * @param requiredHeight The height of the target to render to
  12689. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12690. * @param depthStencilTexture The depth stencil texture to use to render
  12691. * @param lodLevel defines le lod level to bind to the frame buffer
  12692. */
  12693. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12694. if (lodLevel === void 0) { lodLevel = 0; }
  12695. if (this._currentRenderTarget) {
  12696. this.unBindFramebuffer(this._currentRenderTarget);
  12697. }
  12698. this._currentRenderTarget = texture;
  12699. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12700. var gl = this._gl;
  12701. if (texture.isCube) {
  12702. if (faceIndex === undefined) {
  12703. faceIndex = 0;
  12704. }
  12705. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12706. if (depthStencilTexture) {
  12707. if (depthStencilTexture._generateStencilBuffer) {
  12708. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12709. }
  12710. else {
  12711. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12712. }
  12713. }
  12714. }
  12715. if (this._cachedViewport && !forceFullscreenViewport) {
  12716. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12717. }
  12718. else {
  12719. if (!requiredWidth) {
  12720. requiredWidth = texture.width;
  12721. if (lodLevel) {
  12722. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12723. }
  12724. }
  12725. if (!requiredHeight) {
  12726. requiredHeight = texture.height;
  12727. if (lodLevel) {
  12728. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12729. }
  12730. }
  12731. this._viewport(0, 0, requiredWidth, requiredHeight);
  12732. }
  12733. this.wipeCaches();
  12734. };
  12735. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12736. if (this._currentFramebuffer !== framebuffer) {
  12737. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12738. this._currentFramebuffer = framebuffer;
  12739. }
  12740. };
  12741. /**
  12742. * Unbind the current render target texture from the webGL context
  12743. * @param texture defines the render target texture to unbind
  12744. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12745. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12746. */
  12747. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12748. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12749. this._currentRenderTarget = null;
  12750. // If MSAA, we need to bitblt back to main texture
  12751. var gl = this._gl;
  12752. if (texture._MSAAFramebuffer) {
  12753. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12754. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12755. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12756. }
  12757. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12758. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12759. gl.generateMipmap(gl.TEXTURE_2D);
  12760. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12761. }
  12762. if (onBeforeUnbind) {
  12763. if (texture._MSAAFramebuffer) {
  12764. // Bind the correct framebuffer
  12765. this.bindUnboundFramebuffer(texture._framebuffer);
  12766. }
  12767. onBeforeUnbind();
  12768. }
  12769. this.bindUnboundFramebuffer(null);
  12770. };
  12771. /**
  12772. * Unbind a list of render target textures from the webGL context
  12773. * This is used only when drawBuffer extension or webGL2 are active
  12774. * @param textures defines the render target textures to unbind
  12775. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12776. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12777. */
  12778. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12779. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12780. this._currentRenderTarget = null;
  12781. // If MSAA, we need to bitblt back to main texture
  12782. var gl = this._gl;
  12783. if (textures[0]._MSAAFramebuffer) {
  12784. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12785. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12786. var attachments = textures[0]._attachments;
  12787. if (!attachments) {
  12788. attachments = new Array(textures.length);
  12789. textures[0]._attachments = attachments;
  12790. }
  12791. for (var i = 0; i < textures.length; i++) {
  12792. var texture = textures[i];
  12793. for (var j = 0; j < attachments.length; j++) {
  12794. attachments[j] = gl.NONE;
  12795. }
  12796. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12797. gl.readBuffer(attachments[i]);
  12798. gl.drawBuffers(attachments);
  12799. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12800. }
  12801. for (var i = 0; i < attachments.length; i++) {
  12802. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12803. }
  12804. gl.drawBuffers(attachments);
  12805. }
  12806. for (var i = 0; i < textures.length; i++) {
  12807. var texture = textures[i];
  12808. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12809. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12810. gl.generateMipmap(gl.TEXTURE_2D);
  12811. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12812. }
  12813. }
  12814. if (onBeforeUnbind) {
  12815. if (textures[0]._MSAAFramebuffer) {
  12816. // Bind the correct framebuffer
  12817. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12818. }
  12819. onBeforeUnbind();
  12820. }
  12821. this.bindUnboundFramebuffer(null);
  12822. };
  12823. /**
  12824. * Force the mipmap generation for the given render target texture
  12825. * @param texture defines the render target texture to use
  12826. */
  12827. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12828. if (texture.generateMipMaps) {
  12829. var gl = this._gl;
  12830. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12831. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12833. }
  12834. };
  12835. /**
  12836. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12837. */
  12838. Engine.prototype.flushFramebuffer = function () {
  12839. this._gl.flush();
  12840. };
  12841. /**
  12842. * Unbind the current render target and bind the default framebuffer
  12843. */
  12844. Engine.prototype.restoreDefaultFramebuffer = function () {
  12845. if (this._currentRenderTarget) {
  12846. this.unBindFramebuffer(this._currentRenderTarget);
  12847. }
  12848. else {
  12849. this.bindUnboundFramebuffer(null);
  12850. }
  12851. if (this._cachedViewport) {
  12852. this.setViewport(this._cachedViewport);
  12853. }
  12854. this.wipeCaches();
  12855. };
  12856. // UBOs
  12857. /**
  12858. * Create an uniform buffer
  12859. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12860. * @param elements defines the content of the uniform buffer
  12861. * @returns the webGL uniform buffer
  12862. */
  12863. Engine.prototype.createUniformBuffer = function (elements) {
  12864. var ubo = this._gl.createBuffer();
  12865. if (!ubo) {
  12866. throw new Error("Unable to create uniform buffer");
  12867. }
  12868. this.bindUniformBuffer(ubo);
  12869. if (elements instanceof Float32Array) {
  12870. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12871. }
  12872. else {
  12873. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12874. }
  12875. this.bindUniformBuffer(null);
  12876. ubo.references = 1;
  12877. return ubo;
  12878. };
  12879. /**
  12880. * Create a dynamic uniform buffer
  12881. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12882. * @param elements defines the content of the uniform buffer
  12883. * @returns the webGL uniform buffer
  12884. */
  12885. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12886. var ubo = this._gl.createBuffer();
  12887. if (!ubo) {
  12888. throw new Error("Unable to create dynamic uniform buffer");
  12889. }
  12890. this.bindUniformBuffer(ubo);
  12891. if (elements instanceof Float32Array) {
  12892. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12893. }
  12894. else {
  12895. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12896. }
  12897. this.bindUniformBuffer(null);
  12898. ubo.references = 1;
  12899. return ubo;
  12900. };
  12901. /**
  12902. * Update an existing uniform buffer
  12903. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12904. * @param uniformBuffer defines the target uniform buffer
  12905. * @param elements defines the content to update
  12906. * @param offset defines the offset in the uniform buffer where update should start
  12907. * @param count defines the size of the data to update
  12908. */
  12909. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12910. this.bindUniformBuffer(uniformBuffer);
  12911. if (offset === undefined) {
  12912. offset = 0;
  12913. }
  12914. if (count === undefined) {
  12915. if (elements instanceof Float32Array) {
  12916. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12917. }
  12918. else {
  12919. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12920. }
  12921. }
  12922. else {
  12923. if (elements instanceof Float32Array) {
  12924. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12925. }
  12926. else {
  12927. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12928. }
  12929. }
  12930. this.bindUniformBuffer(null);
  12931. };
  12932. // VBOs
  12933. Engine.prototype._resetVertexBufferBinding = function () {
  12934. this.bindArrayBuffer(null);
  12935. this._cachedVertexBuffers = null;
  12936. };
  12937. /**
  12938. * Creates a vertex buffer
  12939. * @param data the data for the vertex buffer
  12940. * @returns the new WebGL static buffer
  12941. */
  12942. Engine.prototype.createVertexBuffer = function (data) {
  12943. var vbo = this._gl.createBuffer();
  12944. if (!vbo) {
  12945. throw new Error("Unable to create vertex buffer");
  12946. }
  12947. this.bindArrayBuffer(vbo);
  12948. if (data instanceof Array) {
  12949. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  12950. }
  12951. else {
  12952. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  12953. }
  12954. this._resetVertexBufferBinding();
  12955. vbo.references = 1;
  12956. return vbo;
  12957. };
  12958. /**
  12959. * Creates a dynamic vertex buffer
  12960. * @param data the data for the dynamic vertex buffer
  12961. * @returns the new WebGL dynamic buffer
  12962. */
  12963. Engine.prototype.createDynamicVertexBuffer = function (data) {
  12964. var vbo = this._gl.createBuffer();
  12965. if (!vbo) {
  12966. throw new Error("Unable to create dynamic vertex buffer");
  12967. }
  12968. this.bindArrayBuffer(vbo);
  12969. if (data instanceof Array) {
  12970. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  12971. }
  12972. else {
  12973. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  12974. }
  12975. this._resetVertexBufferBinding();
  12976. vbo.references = 1;
  12977. return vbo;
  12978. };
  12979. /**
  12980. * Update a dynamic index buffer
  12981. * @param indexBuffer defines the target index buffer
  12982. * @param indices defines the data to update
  12983. * @param offset defines the offset in the target index buffer where update should start
  12984. */
  12985. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12986. if (offset === void 0) { offset = 0; }
  12987. // Force cache update
  12988. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12989. this.bindIndexBuffer(indexBuffer);
  12990. var arrayBuffer;
  12991. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12992. arrayBuffer = indices;
  12993. }
  12994. else {
  12995. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12996. }
  12997. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12998. this._resetIndexBufferBinding();
  12999. };
  13000. /**
  13001. * Updates a dynamic vertex buffer.
  13002. * @param vertexBuffer the vertex buffer to update
  13003. * @param data the data used to update the vertex buffer
  13004. * @param byteOffset the byte offset of the data
  13005. * @param byteLength the byte length of the data
  13006. */
  13007. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13008. this.bindArrayBuffer(vertexBuffer);
  13009. if (byteOffset === undefined) {
  13010. byteOffset = 0;
  13011. }
  13012. if (byteLength === undefined) {
  13013. if (data instanceof Array) {
  13014. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13015. }
  13016. else {
  13017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13018. }
  13019. }
  13020. else {
  13021. if (data instanceof Array) {
  13022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13023. }
  13024. else {
  13025. if (data instanceof ArrayBuffer) {
  13026. data = new Uint8Array(data, byteOffset, byteLength);
  13027. }
  13028. else {
  13029. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13030. }
  13031. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13032. }
  13033. }
  13034. this._resetVertexBufferBinding();
  13035. };
  13036. Engine.prototype._resetIndexBufferBinding = function () {
  13037. this.bindIndexBuffer(null);
  13038. this._cachedIndexBuffer = null;
  13039. };
  13040. /**
  13041. * Creates a new index buffer
  13042. * @param indices defines the content of the index buffer
  13043. * @param updatable defines if the index buffer must be updatable
  13044. * @returns a new webGL buffer
  13045. */
  13046. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13047. var vbo = this._gl.createBuffer();
  13048. if (!vbo) {
  13049. throw new Error("Unable to create index buffer");
  13050. }
  13051. this.bindIndexBuffer(vbo);
  13052. // Check for 32 bits indices
  13053. var arrayBuffer;
  13054. var need32Bits = false;
  13055. if (indices instanceof Uint16Array) {
  13056. arrayBuffer = indices;
  13057. }
  13058. else {
  13059. //check 32 bit support
  13060. if (this._caps.uintIndices) {
  13061. if (indices instanceof Uint32Array) {
  13062. arrayBuffer = indices;
  13063. need32Bits = true;
  13064. }
  13065. else {
  13066. //number[] or Int32Array, check if 32 bit is necessary
  13067. for (var index = 0; index < indices.length; index++) {
  13068. if (indices[index] > 65535) {
  13069. need32Bits = true;
  13070. break;
  13071. }
  13072. }
  13073. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13074. }
  13075. }
  13076. else {
  13077. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13078. arrayBuffer = new Uint16Array(indices);
  13079. }
  13080. }
  13081. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13082. this._resetIndexBufferBinding();
  13083. vbo.references = 1;
  13084. vbo.is32Bits = need32Bits;
  13085. return vbo;
  13086. };
  13087. /**
  13088. * Bind a webGL buffer to the webGL context
  13089. * @param buffer defines the buffer to bind
  13090. */
  13091. Engine.prototype.bindArrayBuffer = function (buffer) {
  13092. if (!this._vaoRecordInProgress) {
  13093. this._unbindVertexArrayObject();
  13094. }
  13095. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13096. };
  13097. /**
  13098. * Bind an uniform buffer to the current webGL context
  13099. * @param buffer defines the buffer to bind
  13100. */
  13101. Engine.prototype.bindUniformBuffer = function (buffer) {
  13102. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13103. };
  13104. /**
  13105. * Bind a buffer to the current webGL context at a given location
  13106. * @param buffer defines the buffer to bind
  13107. * @param location defines the index where to bind the buffer
  13108. */
  13109. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13110. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13111. };
  13112. /**
  13113. * Bind a specific block at a given index in a specific shader program
  13114. * @param shaderProgram defines the shader program
  13115. * @param blockName defines the block name
  13116. * @param index defines the index where to bind the block
  13117. */
  13118. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13119. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13120. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13121. };
  13122. ;
  13123. Engine.prototype.bindIndexBuffer = function (buffer) {
  13124. if (!this._vaoRecordInProgress) {
  13125. this._unbindVertexArrayObject();
  13126. }
  13127. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13128. };
  13129. Engine.prototype.bindBuffer = function (buffer, target) {
  13130. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13131. this._gl.bindBuffer(target, buffer);
  13132. this._currentBoundBuffer[target] = buffer;
  13133. }
  13134. };
  13135. /**
  13136. * update the bound buffer with the given data
  13137. * @param data defines the data to update
  13138. */
  13139. Engine.prototype.updateArrayBuffer = function (data) {
  13140. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13141. };
  13142. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13143. var pointer = this._currentBufferPointers[indx];
  13144. var changed = false;
  13145. if (!pointer.active) {
  13146. changed = true;
  13147. pointer.active = true;
  13148. pointer.index = indx;
  13149. pointer.size = size;
  13150. pointer.type = type;
  13151. pointer.normalized = normalized;
  13152. pointer.stride = stride;
  13153. pointer.offset = offset;
  13154. pointer.buffer = buffer;
  13155. }
  13156. else {
  13157. if (pointer.buffer !== buffer) {
  13158. pointer.buffer = buffer;
  13159. changed = true;
  13160. }
  13161. if (pointer.size !== size) {
  13162. pointer.size = size;
  13163. changed = true;
  13164. }
  13165. if (pointer.type !== type) {
  13166. pointer.type = type;
  13167. changed = true;
  13168. }
  13169. if (pointer.normalized !== normalized) {
  13170. pointer.normalized = normalized;
  13171. changed = true;
  13172. }
  13173. if (pointer.stride !== stride) {
  13174. pointer.stride = stride;
  13175. changed = true;
  13176. }
  13177. if (pointer.offset !== offset) {
  13178. pointer.offset = offset;
  13179. changed = true;
  13180. }
  13181. }
  13182. if (changed || this._vaoRecordInProgress) {
  13183. this.bindArrayBuffer(buffer);
  13184. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13185. }
  13186. };
  13187. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13188. if (indexBuffer == null) {
  13189. return;
  13190. }
  13191. if (this._cachedIndexBuffer !== indexBuffer) {
  13192. this._cachedIndexBuffer = indexBuffer;
  13193. this.bindIndexBuffer(indexBuffer);
  13194. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13195. }
  13196. };
  13197. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13198. var attributes = effect.getAttributesNames();
  13199. if (!this._vaoRecordInProgress) {
  13200. this._unbindVertexArrayObject();
  13201. }
  13202. this.unbindAllAttributes();
  13203. for (var index = 0; index < attributes.length; index++) {
  13204. var order = effect.getAttributeLocation(index);
  13205. if (order >= 0) {
  13206. var vertexBuffer = vertexBuffers[attributes[index]];
  13207. if (!vertexBuffer) {
  13208. continue;
  13209. }
  13210. this._gl.enableVertexAttribArray(order);
  13211. if (!this._vaoRecordInProgress) {
  13212. this._vertexAttribArraysEnabled[order] = true;
  13213. }
  13214. var buffer = vertexBuffer.getBuffer();
  13215. if (buffer) {
  13216. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13217. if (vertexBuffer.getIsInstanced()) {
  13218. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13219. if (!this._vaoRecordInProgress) {
  13220. this._currentInstanceLocations.push(order);
  13221. this._currentInstanceBuffers.push(buffer);
  13222. }
  13223. }
  13224. }
  13225. }
  13226. }
  13227. };
  13228. /**
  13229. * Records a vertex array object
  13230. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13231. * @param vertexBuffers defines the list of vertex buffers to store
  13232. * @param indexBuffer defines the index buffer to store
  13233. * @param effect defines the effect to store
  13234. * @returns the new vertex array object
  13235. */
  13236. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13237. var vao = this._gl.createVertexArray();
  13238. this._vaoRecordInProgress = true;
  13239. this._gl.bindVertexArray(vao);
  13240. this._mustWipeVertexAttributes = true;
  13241. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13242. this.bindIndexBuffer(indexBuffer);
  13243. this._vaoRecordInProgress = false;
  13244. this._gl.bindVertexArray(null);
  13245. return vao;
  13246. };
  13247. /**
  13248. * Bind a specific vertex array object
  13249. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13250. * @param vertexArrayObject defines the vertex array object to bind
  13251. * @param indexBuffer defines the index buffer to bind
  13252. */
  13253. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13254. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13255. this._cachedVertexArrayObject = vertexArrayObject;
  13256. this._gl.bindVertexArray(vertexArrayObject);
  13257. this._cachedVertexBuffers = null;
  13258. this._cachedIndexBuffer = null;
  13259. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13260. this._mustWipeVertexAttributes = true;
  13261. }
  13262. };
  13263. /**
  13264. * Bind webGl buffers directly to the webGL context
  13265. * @param vertexBuffer defines the vertex buffer to bind
  13266. * @param indexBuffer defines the index buffer to bind
  13267. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13268. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13269. * @param effect defines the effect associated with the vertex buffer
  13270. */
  13271. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13272. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13273. this._cachedVertexBuffers = vertexBuffer;
  13274. this._cachedEffectForVertexBuffers = effect;
  13275. var attributesCount = effect.getAttributesCount();
  13276. this._unbindVertexArrayObject();
  13277. this.unbindAllAttributes();
  13278. var offset = 0;
  13279. for (var index = 0; index < attributesCount; index++) {
  13280. if (index < vertexDeclaration.length) {
  13281. var order = effect.getAttributeLocation(index);
  13282. if (order >= 0) {
  13283. this._gl.enableVertexAttribArray(order);
  13284. this._vertexAttribArraysEnabled[order] = true;
  13285. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13286. }
  13287. offset += vertexDeclaration[index] * 4;
  13288. }
  13289. }
  13290. }
  13291. this._bindIndexBufferWithCache(indexBuffer);
  13292. };
  13293. Engine.prototype._unbindVertexArrayObject = function () {
  13294. if (!this._cachedVertexArrayObject) {
  13295. return;
  13296. }
  13297. this._cachedVertexArrayObject = null;
  13298. this._gl.bindVertexArray(null);
  13299. };
  13300. /**
  13301. * Bind a list of vertex buffers to the webGL context
  13302. * @param vertexBuffers defines the list of vertex buffers to bind
  13303. * @param indexBuffer defines the index buffer to bind
  13304. * @param effect defines the effect associated with the vertex buffers
  13305. */
  13306. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13307. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13308. this._cachedVertexBuffers = vertexBuffers;
  13309. this._cachedEffectForVertexBuffers = effect;
  13310. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13311. }
  13312. this._bindIndexBufferWithCache(indexBuffer);
  13313. };
  13314. /**
  13315. * Unbind all instance attributes
  13316. */
  13317. Engine.prototype.unbindInstanceAttributes = function () {
  13318. var boundBuffer;
  13319. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13320. var instancesBuffer = this._currentInstanceBuffers[i];
  13321. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13322. boundBuffer = instancesBuffer;
  13323. this.bindArrayBuffer(instancesBuffer);
  13324. }
  13325. var offsetLocation = this._currentInstanceLocations[i];
  13326. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13327. }
  13328. this._currentInstanceBuffers.length = 0;
  13329. this._currentInstanceLocations.length = 0;
  13330. };
  13331. /**
  13332. * Release and free the memory of a vertex array object
  13333. * @param vao defines the vertex array object to delete
  13334. */
  13335. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13336. this._gl.deleteVertexArray(vao);
  13337. };
  13338. /** @hidden */
  13339. Engine.prototype._releaseBuffer = function (buffer) {
  13340. buffer.references--;
  13341. if (buffer.references === 0) {
  13342. this._gl.deleteBuffer(buffer);
  13343. return true;
  13344. }
  13345. return false;
  13346. };
  13347. /**
  13348. * Creates a webGL buffer to use with instanciation
  13349. * @param capacity defines the size of the buffer
  13350. * @returns the webGL buffer
  13351. */
  13352. Engine.prototype.createInstancesBuffer = function (capacity) {
  13353. var buffer = this._gl.createBuffer();
  13354. if (!buffer) {
  13355. throw new Error("Unable to create instance buffer");
  13356. }
  13357. buffer.capacity = capacity;
  13358. this.bindArrayBuffer(buffer);
  13359. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13360. return buffer;
  13361. };
  13362. /**
  13363. * Delete a webGL buffer used with instanciation
  13364. * @param buffer defines the webGL buffer to delete
  13365. */
  13366. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13367. this._gl.deleteBuffer(buffer);
  13368. };
  13369. /**
  13370. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13371. * @param instancesBuffer defines the webGL buffer to update and bind
  13372. * @param data defines the data to store in the buffer
  13373. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13374. */
  13375. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13376. this.bindArrayBuffer(instancesBuffer);
  13377. if (data) {
  13378. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13379. }
  13380. if (offsetLocations[0].index !== undefined) {
  13381. var stride = 0;
  13382. for (var i = 0; i < offsetLocations.length; i++) {
  13383. var ai = offsetLocations[i];
  13384. stride += ai.attributeSize * 4;
  13385. }
  13386. for (var i = 0; i < offsetLocations.length; i++) {
  13387. var ai = offsetLocations[i];
  13388. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13389. this._gl.enableVertexAttribArray(ai.index);
  13390. this._vertexAttribArraysEnabled[ai.index] = true;
  13391. }
  13392. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13393. this._gl.vertexAttribDivisor(ai.index, 1);
  13394. this._currentInstanceLocations.push(ai.index);
  13395. this._currentInstanceBuffers.push(instancesBuffer);
  13396. }
  13397. }
  13398. else {
  13399. for (var index = 0; index < 4; index++) {
  13400. var offsetLocation = offsetLocations[index];
  13401. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13402. this._gl.enableVertexAttribArray(offsetLocation);
  13403. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13404. }
  13405. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13406. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13407. this._currentInstanceLocations.push(offsetLocation);
  13408. this._currentInstanceBuffers.push(instancesBuffer);
  13409. }
  13410. }
  13411. };
  13412. /**
  13413. * Apply all cached states (depth, culling, stencil and alpha)
  13414. */
  13415. Engine.prototype.applyStates = function () {
  13416. this._depthCullingState.apply(this._gl);
  13417. this._stencilState.apply(this._gl);
  13418. this._alphaState.apply(this._gl);
  13419. };
  13420. /**
  13421. * Send a draw order
  13422. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13423. * @param indexStart defines the starting index
  13424. * @param indexCount defines the number of index to draw
  13425. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13426. */
  13427. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13428. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13429. };
  13430. /**
  13431. * Draw a list of points
  13432. * @param verticesStart defines the index of first vertex to draw
  13433. * @param verticesCount defines the count of vertices to draw
  13434. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13435. */
  13436. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13437. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13438. };
  13439. /**
  13440. * Draw a list of unindexed primitives
  13441. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13442. * @param verticesStart defines the index of first vertex to draw
  13443. * @param verticesCount defines the count of vertices to draw
  13444. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13445. */
  13446. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13447. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13448. };
  13449. /**
  13450. * Draw a list of indexed primitives
  13451. * @param fillMode defines the primitive to use
  13452. * @param indexStart defines the starting index
  13453. * @param indexCount defines the number of index to draw
  13454. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13455. */
  13456. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13457. // Apply states
  13458. this.applyStates();
  13459. this._drawCalls.addCount(1, false);
  13460. // Render
  13461. var drawMode = this._drawMode(fillMode);
  13462. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13463. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13464. if (instancesCount) {
  13465. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13466. }
  13467. else {
  13468. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13469. }
  13470. };
  13471. /**
  13472. * Draw a list of unindexed primitives
  13473. * @param fillMode defines the primitive to use
  13474. * @param verticesStart defines the index of first vertex to draw
  13475. * @param verticesCount defines the count of vertices to draw
  13476. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13477. */
  13478. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13479. // Apply states
  13480. this.applyStates();
  13481. this._drawCalls.addCount(1, false);
  13482. var drawMode = this._drawMode(fillMode);
  13483. if (instancesCount) {
  13484. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13485. }
  13486. else {
  13487. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13488. }
  13489. };
  13490. Engine.prototype._drawMode = function (fillMode) {
  13491. switch (fillMode) {
  13492. // Triangle views
  13493. case BABYLON.Material.TriangleFillMode:
  13494. return this._gl.TRIANGLES;
  13495. case BABYLON.Material.PointFillMode:
  13496. return this._gl.POINTS;
  13497. case BABYLON.Material.WireFrameFillMode:
  13498. return this._gl.LINES;
  13499. // Draw modes
  13500. case BABYLON.Material.PointListDrawMode:
  13501. return this._gl.POINTS;
  13502. case BABYLON.Material.LineListDrawMode:
  13503. return this._gl.LINES;
  13504. case BABYLON.Material.LineLoopDrawMode:
  13505. return this._gl.LINE_LOOP;
  13506. case BABYLON.Material.LineStripDrawMode:
  13507. return this._gl.LINE_STRIP;
  13508. case BABYLON.Material.TriangleStripDrawMode:
  13509. return this._gl.TRIANGLE_STRIP;
  13510. case BABYLON.Material.TriangleFanDrawMode:
  13511. return this._gl.TRIANGLE_FAN;
  13512. default:
  13513. return this._gl.TRIANGLES;
  13514. }
  13515. };
  13516. // Shaders
  13517. /** @hidden */
  13518. Engine.prototype._releaseEffect = function (effect) {
  13519. if (this._compiledEffects[effect._key]) {
  13520. delete this._compiledEffects[effect._key];
  13521. this._deleteProgram(effect.getProgram());
  13522. }
  13523. };
  13524. /** @hidden */
  13525. Engine.prototype._deleteProgram = function (program) {
  13526. if (program) {
  13527. program.__SPECTOR_rebuildProgram = null;
  13528. if (program.transformFeedback) {
  13529. this.deleteTransformFeedback(program.transformFeedback);
  13530. program.transformFeedback = null;
  13531. }
  13532. this._gl.deleteProgram(program);
  13533. }
  13534. };
  13535. /**
  13536. * Create a new effect (used to store vertex/fragment shaders)
  13537. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13538. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13539. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13540. * @param samplers defines an array of string used to represent textures
  13541. * @param defines defines the string containing the defines to use to compile the shaders
  13542. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13543. * @param onCompiled defines a function to call when the effect creation is successful
  13544. * @param onError defines a function to call when the effect creation has failed
  13545. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13546. * @returns the new Effect
  13547. */
  13548. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13549. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13550. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13551. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13552. if (this._compiledEffects[name]) {
  13553. var compiledEffect = this._compiledEffects[name];
  13554. if (onCompiled && compiledEffect.isReady()) {
  13555. onCompiled(compiledEffect);
  13556. }
  13557. return compiledEffect;
  13558. }
  13559. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13560. effect._key = name;
  13561. this._compiledEffects[name] = effect;
  13562. return effect;
  13563. };
  13564. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13565. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13566. };
  13567. ;
  13568. Engine.prototype._compileRawShader = function (source, type) {
  13569. var gl = this._gl;
  13570. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13571. gl.shaderSource(shader, source);
  13572. gl.compileShader(shader);
  13573. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13574. var log = gl.getShaderInfoLog(shader);
  13575. if (log) {
  13576. throw new Error(log);
  13577. }
  13578. }
  13579. if (!shader) {
  13580. throw new Error("Something went wrong while compile the shader.");
  13581. }
  13582. return shader;
  13583. };
  13584. ;
  13585. /**
  13586. * Directly creates a webGL program
  13587. * @param vertexCode defines the vertex shader code to use
  13588. * @param fragmentCode defines the fragment shader code to use
  13589. * @param context defines the webGL context to use (if not set, the current one will be used)
  13590. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13591. * @returns the new webGL program
  13592. */
  13593. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13594. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13595. context = context || this._gl;
  13596. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13597. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13598. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13599. };
  13600. /**
  13601. * Creates a webGL program
  13602. * @param vertexCode defines the vertex shader code to use
  13603. * @param fragmentCode defines the fragment shader code to use
  13604. * @param defines defines the string containing the defines to use to compile the shaders
  13605. * @param context defines the webGL context to use (if not set, the current one will be used)
  13606. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13607. * @returns the new webGL program
  13608. */
  13609. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13610. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13611. context = context || this._gl;
  13612. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13613. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13614. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13615. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13616. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13617. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13618. return program;
  13619. };
  13620. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13621. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13622. var shaderProgram = context.createProgram();
  13623. if (!shaderProgram) {
  13624. throw new Error("Unable to create program");
  13625. }
  13626. context.attachShader(shaderProgram, vertexShader);
  13627. context.attachShader(shaderProgram, fragmentShader);
  13628. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13629. var transformFeedback = this.createTransformFeedback();
  13630. this.bindTransformFeedback(transformFeedback);
  13631. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13632. shaderProgram.transformFeedback = transformFeedback;
  13633. }
  13634. context.linkProgram(shaderProgram);
  13635. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13636. this.bindTransformFeedback(null);
  13637. }
  13638. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13639. if (!linked) {
  13640. var error = context.getProgramInfoLog(shaderProgram);
  13641. if (error) {
  13642. throw new Error(error);
  13643. }
  13644. }
  13645. if (this.validateShaderPrograms) {
  13646. context.validateProgram(shaderProgram);
  13647. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13648. if (!validated) {
  13649. var error = context.getProgramInfoLog(shaderProgram);
  13650. if (error) {
  13651. throw new Error(error);
  13652. }
  13653. }
  13654. }
  13655. context.deleteShader(vertexShader);
  13656. context.deleteShader(fragmentShader);
  13657. return shaderProgram;
  13658. };
  13659. /**
  13660. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13661. * @param shaderProgram defines the webGL program to use
  13662. * @param uniformsNames defines the list of uniform names
  13663. * @returns an array of webGL uniform locations
  13664. */
  13665. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13666. var results = new Array();
  13667. for (var index = 0; index < uniformsNames.length; index++) {
  13668. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13669. }
  13670. return results;
  13671. };
  13672. /**
  13673. * Gets the lsit of active attributes for a given webGL program
  13674. * @param shaderProgram defines the webGL program to use
  13675. * @param attributesNames defines the list of attribute names to get
  13676. * @returns an array of indices indicating the offset of each attribute
  13677. */
  13678. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13679. var results = [];
  13680. for (var index = 0; index < attributesNames.length; index++) {
  13681. try {
  13682. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13683. }
  13684. catch (e) {
  13685. results.push(-1);
  13686. }
  13687. }
  13688. return results;
  13689. };
  13690. /**
  13691. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13692. * @param effect defines the effect to activate
  13693. */
  13694. Engine.prototype.enableEffect = function (effect) {
  13695. if (!effect) {
  13696. return;
  13697. }
  13698. // Use program
  13699. this.bindSamplers(effect);
  13700. this._currentEffect = effect;
  13701. if (effect.onBind) {
  13702. effect.onBind(effect);
  13703. }
  13704. effect.onBindObservable.notifyObservers(effect);
  13705. };
  13706. /**
  13707. * Set the value of an uniform to an array of int32
  13708. * @param uniform defines the webGL uniform location where to store the value
  13709. * @param array defines the array of int32 to store
  13710. */
  13711. Engine.prototype.setIntArray = function (uniform, array) {
  13712. if (!uniform)
  13713. return;
  13714. this._gl.uniform1iv(uniform, array);
  13715. };
  13716. /**
  13717. * Set the value of an uniform to an array of int32 (stored as vec2)
  13718. * @param uniform defines the webGL uniform location where to store the value
  13719. * @param array defines the array of int32 to store
  13720. */
  13721. Engine.prototype.setIntArray2 = function (uniform, array) {
  13722. if (!uniform || array.length % 2 !== 0)
  13723. return;
  13724. this._gl.uniform2iv(uniform, array);
  13725. };
  13726. /**
  13727. * Set the value of an uniform to an array of int32 (stored as vec3)
  13728. * @param uniform defines the webGL uniform location where to store the value
  13729. * @param array defines the array of int32 to store
  13730. */
  13731. Engine.prototype.setIntArray3 = function (uniform, array) {
  13732. if (!uniform || array.length % 3 !== 0)
  13733. return;
  13734. this._gl.uniform3iv(uniform, array);
  13735. };
  13736. /**
  13737. * Set the value of an uniform to an array of int32 (stored as vec4)
  13738. * @param uniform defines the webGL uniform location where to store the value
  13739. * @param array defines the array of int32 to store
  13740. */
  13741. Engine.prototype.setIntArray4 = function (uniform, array) {
  13742. if (!uniform || array.length % 4 !== 0)
  13743. return;
  13744. this._gl.uniform4iv(uniform, array);
  13745. };
  13746. /**
  13747. * Set the value of an uniform to an array of float32
  13748. * @param uniform defines the webGL uniform location where to store the value
  13749. * @param array defines the array of float32 to store
  13750. */
  13751. Engine.prototype.setFloatArray = function (uniform, array) {
  13752. if (!uniform)
  13753. return;
  13754. this._gl.uniform1fv(uniform, array);
  13755. };
  13756. /**
  13757. * Set the value of an uniform to an array of float32 (stored as vec2)
  13758. * @param uniform defines the webGL uniform location where to store the value
  13759. * @param array defines the array of float32 to store
  13760. */
  13761. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13762. if (!uniform || array.length % 2 !== 0)
  13763. return;
  13764. this._gl.uniform2fv(uniform, array);
  13765. };
  13766. /**
  13767. * Set the value of an uniform to an array of float32 (stored as vec3)
  13768. * @param uniform defines the webGL uniform location where to store the value
  13769. * @param array defines the array of float32 to store
  13770. */
  13771. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13772. if (!uniform || array.length % 3 !== 0)
  13773. return;
  13774. this._gl.uniform3fv(uniform, array);
  13775. };
  13776. /**
  13777. * Set the value of an uniform to an array of float32 (stored as vec4)
  13778. * @param uniform defines the webGL uniform location where to store the value
  13779. * @param array defines the array of float32 to store
  13780. */
  13781. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13782. if (!uniform || array.length % 4 !== 0)
  13783. return;
  13784. this._gl.uniform4fv(uniform, array);
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of number
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of number to store
  13790. */
  13791. Engine.prototype.setArray = function (uniform, array) {
  13792. if (!uniform)
  13793. return;
  13794. this._gl.uniform1fv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of number (stored as vec2)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of number to store
  13800. */
  13801. Engine.prototype.setArray2 = function (uniform, array) {
  13802. if (!uniform || array.length % 2 !== 0)
  13803. return;
  13804. this._gl.uniform2fv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of number (stored as vec3)
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of number to store
  13810. */
  13811. Engine.prototype.setArray3 = function (uniform, array) {
  13812. if (!uniform || array.length % 3 !== 0)
  13813. return;
  13814. this._gl.uniform3fv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of number (stored as vec4)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of number to store
  13820. */
  13821. Engine.prototype.setArray4 = function (uniform, array) {
  13822. if (!uniform || array.length % 4 !== 0)
  13823. return;
  13824. this._gl.uniform4fv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32 (stored as matrices)
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param matrices defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setMatrices = function (uniform, matrices) {
  13832. if (!uniform)
  13833. return;
  13834. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to a matrix
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param matrix defines the matrix to store
  13840. */
  13841. Engine.prototype.setMatrix = function (uniform, matrix) {
  13842. if (!uniform)
  13843. return;
  13844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13845. };
  13846. /**
  13847. * Set the value of an uniform to a matrix (3x3)
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13850. */
  13851. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13852. if (!uniform)
  13853. return;
  13854. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to a matrix (2x2)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13860. */
  13861. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13862. if (!uniform)
  13863. return;
  13864. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to a number (int)
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param value defines the int number to store
  13870. */
  13871. Engine.prototype.setInt = function (uniform, value) {
  13872. if (!uniform)
  13873. return;
  13874. this._gl.uniform1i(uniform, value);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to a number (float)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param value defines the float number to store
  13880. */
  13881. Engine.prototype.setFloat = function (uniform, value) {
  13882. if (!uniform)
  13883. return;
  13884. this._gl.uniform1f(uniform, value);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to a vec2
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param x defines the 1st component of the value
  13890. * @param y defines the 2nd component of the value
  13891. */
  13892. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13893. if (!uniform)
  13894. return;
  13895. this._gl.uniform2f(uniform, x, y);
  13896. };
  13897. /**
  13898. * Set the value of an uniform to a vec3
  13899. * @param uniform defines the webGL uniform location where to store the value
  13900. * @param x defines the 1st component of the value
  13901. * @param y defines the 2nd component of the value
  13902. * @param z defines the 3rd component of the value
  13903. */
  13904. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13905. if (!uniform)
  13906. return;
  13907. this._gl.uniform3f(uniform, x, y, z);
  13908. };
  13909. /**
  13910. * Set the value of an uniform to a boolean
  13911. * @param uniform defines the webGL uniform location where to store the value
  13912. * @param bool defines the boolean to store
  13913. */
  13914. Engine.prototype.setBool = function (uniform, bool) {
  13915. if (!uniform)
  13916. return;
  13917. this._gl.uniform1i(uniform, bool);
  13918. };
  13919. /**
  13920. * Set the value of an uniform to a vec4
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param x defines the 1st component of the value
  13923. * @param y defines the 2nd component of the value
  13924. * @param z defines the 3rd component of the value
  13925. * @param w defines the 4th component of the value
  13926. */
  13927. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13928. if (!uniform)
  13929. return;
  13930. this._gl.uniform4f(uniform, x, y, z, w);
  13931. };
  13932. /**
  13933. * Set the value of an uniform to a Color3
  13934. * @param uniform defines the webGL uniform location where to store the value
  13935. * @param color3 defines the color to store
  13936. */
  13937. Engine.prototype.setColor3 = function (uniform, color3) {
  13938. if (!uniform)
  13939. return;
  13940. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  13941. };
  13942. /**
  13943. * Set the value of an uniform to a Color3 and an alpha value
  13944. * @param uniform defines the webGL uniform location where to store the value
  13945. * @param color3 defines the color to store
  13946. * @param alpha defines the alpha component to store
  13947. */
  13948. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  13949. if (!uniform)
  13950. return;
  13951. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  13952. };
  13953. /**
  13954. * Sets a Color4 on a uniform variable
  13955. * @param uniform defines the uniform location
  13956. * @param color4 defines the value to be set
  13957. */
  13958. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  13959. if (!uniform)
  13960. return;
  13961. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  13962. };
  13963. // States
  13964. /**
  13965. * Set various states to the webGL context
  13966. * @param culling defines backface culling state
  13967. * @param zOffset defines the value to apply to zOffset (0 by default)
  13968. * @param force defines if states must be applied even if cache is up to date
  13969. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  13970. */
  13971. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  13972. if (zOffset === void 0) { zOffset = 0; }
  13973. if (reverseSide === void 0) { reverseSide = false; }
  13974. // Culling
  13975. if (this._depthCullingState.cull !== culling || force) {
  13976. this._depthCullingState.cull = culling;
  13977. }
  13978. // Cull face
  13979. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  13980. if (this._depthCullingState.cullFace !== cullFace || force) {
  13981. this._depthCullingState.cullFace = cullFace;
  13982. }
  13983. // Z offset
  13984. this.setZOffset(zOffset);
  13985. // Front face
  13986. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  13987. if (this._depthCullingState.frontFace !== frontFace || force) {
  13988. this._depthCullingState.frontFace = frontFace;
  13989. }
  13990. };
  13991. /**
  13992. * Set the z offset to apply to current rendering
  13993. * @param value defines the offset to apply
  13994. */
  13995. Engine.prototype.setZOffset = function (value) {
  13996. this._depthCullingState.zOffset = value;
  13997. };
  13998. /**
  13999. * Gets the current value of the zOffset
  14000. * @returns the current zOffset state
  14001. */
  14002. Engine.prototype.getZOffset = function () {
  14003. return this._depthCullingState.zOffset;
  14004. };
  14005. /**
  14006. * Enable or disable depth buffering
  14007. * @param enable defines the state to set
  14008. */
  14009. Engine.prototype.setDepthBuffer = function (enable) {
  14010. this._depthCullingState.depthTest = enable;
  14011. };
  14012. /**
  14013. * Gets a boolean indicating if depth writing is enabled
  14014. * @returns the current depth writing state
  14015. */
  14016. Engine.prototype.getDepthWrite = function () {
  14017. return this._depthCullingState.depthMask;
  14018. };
  14019. /**
  14020. * Enable or disable depth writing
  14021. * @param enable defines the state to set
  14022. */
  14023. Engine.prototype.setDepthWrite = function (enable) {
  14024. this._depthCullingState.depthMask = enable;
  14025. };
  14026. /**
  14027. * Enable or disable color writing
  14028. * @param enable defines the state to set
  14029. */
  14030. Engine.prototype.setColorWrite = function (enable) {
  14031. this._gl.colorMask(enable, enable, enable, enable);
  14032. this._colorWrite = enable;
  14033. };
  14034. /**
  14035. * Gets a boolean indicating if color writing is enabled
  14036. * @returns the current color writing state
  14037. */
  14038. Engine.prototype.getColorWrite = function () {
  14039. return this._colorWrite;
  14040. };
  14041. /**
  14042. * Sets alpha constants used by some alpha blending modes
  14043. * @param r defines the red component
  14044. * @param g defines the green component
  14045. * @param b defines the blue component
  14046. * @param a defines the alpha component
  14047. */
  14048. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14049. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14050. };
  14051. /**
  14052. * Sets the current alpha mode
  14053. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14054. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14055. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14056. */
  14057. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14058. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14059. if (this._alphaMode === mode) {
  14060. return;
  14061. }
  14062. switch (mode) {
  14063. case Engine.ALPHA_DISABLE:
  14064. this._alphaState.alphaBlend = false;
  14065. break;
  14066. case Engine.ALPHA_PREMULTIPLIED:
  14067. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14068. this._alphaState.alphaBlend = true;
  14069. break;
  14070. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14071. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14072. this._alphaState.alphaBlend = true;
  14073. break;
  14074. case Engine.ALPHA_COMBINE:
  14075. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14076. this._alphaState.alphaBlend = true;
  14077. break;
  14078. case Engine.ALPHA_ONEONE:
  14079. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14080. this._alphaState.alphaBlend = true;
  14081. break;
  14082. case Engine.ALPHA_ADD:
  14083. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14084. this._alphaState.alphaBlend = true;
  14085. break;
  14086. case Engine.ALPHA_SUBTRACT:
  14087. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14088. this._alphaState.alphaBlend = true;
  14089. break;
  14090. case Engine.ALPHA_MULTIPLY:
  14091. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14092. this._alphaState.alphaBlend = true;
  14093. break;
  14094. case Engine.ALPHA_MAXIMIZED:
  14095. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14096. this._alphaState.alphaBlend = true;
  14097. break;
  14098. case Engine.ALPHA_INTERPOLATE:
  14099. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14100. this._alphaState.alphaBlend = true;
  14101. break;
  14102. case Engine.ALPHA_SCREENMODE:
  14103. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14104. this._alphaState.alphaBlend = true;
  14105. break;
  14106. }
  14107. if (!noDepthWriteChange) {
  14108. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14109. }
  14110. this._alphaMode = mode;
  14111. };
  14112. /**
  14113. * Gets the current alpha mode
  14114. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14115. * @returns the current alpha mode
  14116. */
  14117. Engine.prototype.getAlphaMode = function () {
  14118. return this._alphaMode;
  14119. };
  14120. // Textures
  14121. /**
  14122. * Clears the list of texture accessible through engine.
  14123. * This can help preventing texture load conflict due to name collision.
  14124. */
  14125. Engine.prototype.clearInternalTexturesCache = function () {
  14126. this._internalTexturesCache = [];
  14127. };
  14128. /**
  14129. * Force the entire cache to be cleared
  14130. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14131. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14132. */
  14133. Engine.prototype.wipeCaches = function (bruteForce) {
  14134. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14135. return;
  14136. }
  14137. this._currentEffect = null;
  14138. this._unpackFlipYCached = null;
  14139. this._viewportCached.x = 0;
  14140. this._viewportCached.y = 0;
  14141. this._viewportCached.z = 0;
  14142. this._viewportCached.w = 0;
  14143. if (bruteForce) {
  14144. this.resetTextureCache();
  14145. this._currentProgram = null;
  14146. this._stencilState.reset();
  14147. this._depthCullingState.reset();
  14148. this.setDepthFunctionToLessOrEqual();
  14149. this._alphaState.reset();
  14150. }
  14151. this._resetVertexBufferBinding();
  14152. this._cachedIndexBuffer = null;
  14153. this._cachedEffectForVertexBuffers = null;
  14154. this._unbindVertexArrayObject();
  14155. this.bindIndexBuffer(null);
  14156. };
  14157. /**
  14158. * Set the compressed texture format to use, based on the formats you have, and the formats
  14159. * supported by the hardware / browser.
  14160. *
  14161. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14162. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14163. * to API arguments needed to compressed textures. This puts the burden on the container
  14164. * generator to house the arcane code for determining these for current & future formats.
  14165. *
  14166. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14167. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14168. *
  14169. * Note: The result of this call is not taken into account when a texture is base64.
  14170. *
  14171. * @param formatsAvailable defines the list of those format families you have created
  14172. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14173. *
  14174. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14175. * @returns The extension selected.
  14176. */
  14177. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14178. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14179. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14180. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14181. return this._textureFormatInUse = this._texturesSupported[i];
  14182. }
  14183. }
  14184. }
  14185. // actively set format to nothing, to allow this to be called more than once
  14186. // and possibly fail the 2nd time
  14187. this._textureFormatInUse = null;
  14188. return null;
  14189. };
  14190. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14191. var gl = this._gl;
  14192. var magFilter = gl.NEAREST;
  14193. var minFilter = gl.NEAREST;
  14194. switch (samplingMode) {
  14195. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14196. magFilter = gl.LINEAR;
  14197. if (generateMipMaps) {
  14198. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14199. }
  14200. else {
  14201. minFilter = gl.LINEAR;
  14202. }
  14203. break;
  14204. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14205. magFilter = gl.LINEAR;
  14206. if (generateMipMaps) {
  14207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14208. }
  14209. else {
  14210. minFilter = gl.LINEAR;
  14211. }
  14212. break;
  14213. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14214. magFilter = gl.NEAREST;
  14215. if (generateMipMaps) {
  14216. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14217. }
  14218. else {
  14219. minFilter = gl.NEAREST;
  14220. }
  14221. break;
  14222. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14223. magFilter = gl.NEAREST;
  14224. if (generateMipMaps) {
  14225. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14226. }
  14227. else {
  14228. minFilter = gl.NEAREST;
  14229. }
  14230. break;
  14231. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14232. magFilter = gl.NEAREST;
  14233. if (generateMipMaps) {
  14234. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14235. }
  14236. else {
  14237. minFilter = gl.LINEAR;
  14238. }
  14239. break;
  14240. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14241. magFilter = gl.NEAREST;
  14242. if (generateMipMaps) {
  14243. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14244. }
  14245. else {
  14246. minFilter = gl.LINEAR;
  14247. }
  14248. break;
  14249. case Engine.TEXTURE_NEAREST_LINEAR:
  14250. magFilter = gl.NEAREST;
  14251. minFilter = gl.LINEAR;
  14252. break;
  14253. case Engine.TEXTURE_NEAREST_NEAREST:
  14254. magFilter = gl.NEAREST;
  14255. minFilter = gl.NEAREST;
  14256. break;
  14257. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14258. magFilter = gl.LINEAR;
  14259. if (generateMipMaps) {
  14260. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14261. }
  14262. else {
  14263. minFilter = gl.NEAREST;
  14264. }
  14265. break;
  14266. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14267. magFilter = gl.LINEAR;
  14268. if (generateMipMaps) {
  14269. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14270. }
  14271. else {
  14272. minFilter = gl.NEAREST;
  14273. }
  14274. break;
  14275. case Engine.TEXTURE_LINEAR_LINEAR:
  14276. magFilter = gl.LINEAR;
  14277. minFilter = gl.LINEAR;
  14278. break;
  14279. case Engine.TEXTURE_LINEAR_NEAREST:
  14280. magFilter = gl.LINEAR;
  14281. minFilter = gl.NEAREST;
  14282. break;
  14283. }
  14284. return {
  14285. min: minFilter,
  14286. mag: magFilter
  14287. };
  14288. };
  14289. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14290. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14291. var img;
  14292. var onload = function () {
  14293. loadedImages[index] = img;
  14294. loadedImages._internalCount++;
  14295. if (scene) {
  14296. scene._removePendingData(img);
  14297. }
  14298. if (loadedImages._internalCount === 6) {
  14299. onfinish(loadedImages);
  14300. }
  14301. };
  14302. var onerror = function (message, exception) {
  14303. if (scene) {
  14304. scene._removePendingData(img);
  14305. }
  14306. if (onErrorCallBack) {
  14307. onErrorCallBack(message, exception);
  14308. }
  14309. };
  14310. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14311. if (scene) {
  14312. scene._addPendingData(img);
  14313. }
  14314. };
  14315. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14316. if (onError === void 0) { onError = null; }
  14317. var loadedImages = [];
  14318. loadedImages._internalCount = 0;
  14319. for (var index = 0; index < 6; index++) {
  14320. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14321. }
  14322. };
  14323. ;
  14324. /** @hidden */
  14325. Engine.prototype._createTexture = function () {
  14326. var texture = this._gl.createTexture();
  14327. if (!texture) {
  14328. throw new Error("Unable to create texture");
  14329. }
  14330. return texture;
  14331. };
  14332. /**
  14333. * Usually called from BABYLON.Texture.ts.
  14334. * Passed information to create a WebGLTexture
  14335. * @param urlArg defines a value which contains one of the following:
  14336. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14337. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14338. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14339. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14340. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14341. * @param scene needed for loading to the correct scene
  14342. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14343. * @param onLoad optional callback to be called upon successful completion
  14344. * @param onError optional callback to be called upon failure
  14345. * @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
  14346. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14347. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14348. * @param forcedExtension defines the extension to use to pick the right loader
  14349. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14350. */
  14351. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14352. var _this = this;
  14353. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14354. if (onLoad === void 0) { onLoad = null; }
  14355. if (onError === void 0) { onError = null; }
  14356. if (buffer === void 0) { buffer = null; }
  14357. if (fallback === void 0) { fallback = null; }
  14358. if (format === void 0) { format = null; }
  14359. if (forcedExtension === void 0) { forcedExtension = null; }
  14360. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14361. var fromData = url.substr(0, 5) === "data:";
  14362. var fromBlob = url.substr(0, 5) === "blob:";
  14363. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14364. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14365. // establish the file extension, if possible
  14366. var lastDot = url.lastIndexOf('.');
  14367. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14368. var loader = null;
  14369. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14370. var availableLoader = _a[_i];
  14371. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14372. loader = availableLoader;
  14373. break;
  14374. }
  14375. }
  14376. if (loader) {
  14377. url = loader.transformUrl(url, this._textureFormatInUse);
  14378. }
  14379. if (scene) {
  14380. scene._addPendingData(texture);
  14381. }
  14382. texture.url = url;
  14383. texture.generateMipMaps = !noMipmap;
  14384. texture.samplingMode = samplingMode;
  14385. texture.invertY = invertY;
  14386. if (!this._doNotHandleContextLost) {
  14387. // Keep a link to the buffer only if we plan to handle context lost
  14388. texture._buffer = buffer;
  14389. }
  14390. var onLoadObserver = null;
  14391. if (onLoad && !fallback) {
  14392. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14393. }
  14394. if (!fallback)
  14395. this._internalTexturesCache.push(texture);
  14396. var onInternalError = function (message, exception) {
  14397. if (scene) {
  14398. scene._removePendingData(texture);
  14399. }
  14400. var customFallback = false;
  14401. if (loader) {
  14402. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14403. if (fallbackUrl) {
  14404. // Add Back
  14405. customFallback = true;
  14406. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14407. }
  14408. }
  14409. if (!customFallback) {
  14410. if (onLoadObserver) {
  14411. texture.onLoadedObservable.remove(onLoadObserver);
  14412. }
  14413. if (BABYLON.Tools.UseFallbackTexture) {
  14414. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14415. }
  14416. }
  14417. if (onError) {
  14418. onError(message || "Unknown error", exception);
  14419. }
  14420. };
  14421. // processing for non-image formats
  14422. if (loader) {
  14423. var callback = function (data) {
  14424. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14425. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14426. done();
  14427. return false;
  14428. }, samplingMode);
  14429. });
  14430. };
  14431. if (!buffer) {
  14432. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14433. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14434. });
  14435. }
  14436. else {
  14437. callback(buffer);
  14438. }
  14439. }
  14440. else {
  14441. var onload = function (img) {
  14442. if (fromBlob && !_this._doNotHandleContextLost) {
  14443. // We need to store the image if we need to rebuild the texture
  14444. // in case of a webgl context lost
  14445. texture._buffer = img;
  14446. }
  14447. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14448. var gl = _this._gl;
  14449. var isPot = (img.width === potWidth && img.height === potHeight);
  14450. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14451. if (isPot) {
  14452. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14453. return false;
  14454. }
  14455. var maxTextureSize = _this._caps.maxTextureSize;
  14456. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14457. _this._prepareWorkingCanvas();
  14458. if (!_this._workingCanvas || !_this._workingContext) {
  14459. return false;
  14460. }
  14461. _this._workingCanvas.width = potWidth;
  14462. _this._workingCanvas.height = potHeight;
  14463. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14464. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14465. texture.width = potWidth;
  14466. texture.height = potHeight;
  14467. return false;
  14468. }
  14469. else {
  14470. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14471. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14472. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14473. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14478. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14479. _this._releaseTexture(source_1);
  14480. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14481. continuationCallback();
  14482. });
  14483. }
  14484. return true;
  14485. }, samplingMode);
  14486. };
  14487. if (!fromData || isBase64) {
  14488. if (buffer instanceof HTMLImageElement) {
  14489. onload(buffer);
  14490. }
  14491. else {
  14492. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14493. }
  14494. }
  14495. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14496. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14497. }
  14498. else {
  14499. onload(buffer);
  14500. }
  14501. }
  14502. return texture;
  14503. };
  14504. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14505. var _this = this;
  14506. var rtt = this.createRenderTargetTexture({
  14507. width: destination.width,
  14508. height: destination.height,
  14509. }, {
  14510. generateMipMaps: false,
  14511. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14512. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14513. generateDepthBuffer: false,
  14514. generateStencilBuffer: false
  14515. });
  14516. if (!this._rescalePostProcess) {
  14517. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14518. }
  14519. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14520. _this._rescalePostProcess.onApply = function (effect) {
  14521. effect._bindTexture("textureSampler", source);
  14522. };
  14523. var hostingScene = scene;
  14524. if (!hostingScene) {
  14525. hostingScene = _this.scenes[_this.scenes.length - 1];
  14526. }
  14527. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14528. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14529. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14530. _this.unBindFramebuffer(rtt);
  14531. _this._releaseTexture(rtt);
  14532. if (onComplete) {
  14533. onComplete();
  14534. }
  14535. });
  14536. };
  14537. /**
  14538. * Update a raw texture
  14539. * @param texture defines the texture to update
  14540. * @param data defines the data to store in the texture
  14541. * @param format defines the format of the data
  14542. * @param invertY defines if data must be stored with Y axis inverted
  14543. * @param compression defines the compression used (null by default)
  14544. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14545. */
  14546. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14547. if (compression === void 0) { compression = null; }
  14548. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14549. if (!texture) {
  14550. return;
  14551. }
  14552. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14553. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14554. // babylon's internalFormat but gl's texImage2D format
  14555. var internalFormat = this._getInternalFormat(format);
  14556. var textureType = this._getWebGLTextureType(type);
  14557. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14558. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14559. if (!this._doNotHandleContextLost) {
  14560. texture._bufferView = data;
  14561. texture.format = format;
  14562. texture.type = type;
  14563. texture.invertY = invertY;
  14564. texture._compression = compression;
  14565. }
  14566. if (texture.width % 4 !== 0) {
  14567. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14568. }
  14569. if (compression && data) {
  14570. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14571. }
  14572. else {
  14573. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14574. }
  14575. if (texture.generateMipMaps) {
  14576. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14577. }
  14578. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14579. // this.resetTextureCache();
  14580. texture.isReady = true;
  14581. };
  14582. /**
  14583. * Creates a raw texture
  14584. * @param data defines the data to store in the texture
  14585. * @param width defines the width of the texture
  14586. * @param height defines the height of the texture
  14587. * @param format defines the format of the data
  14588. * @param generateMipMaps defines if the engine should generate the mip levels
  14589. * @param invertY defines if data must be stored with Y axis inverted
  14590. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14591. * @param compression defines the compression used (null by default)
  14592. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14593. * @returns the raw texture inside an InternalTexture
  14594. */
  14595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14596. if (compression === void 0) { compression = null; }
  14597. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14598. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14599. texture.baseWidth = width;
  14600. texture.baseHeight = height;
  14601. texture.width = width;
  14602. texture.height = height;
  14603. texture.format = format;
  14604. texture.generateMipMaps = generateMipMaps;
  14605. texture.samplingMode = samplingMode;
  14606. texture.invertY = invertY;
  14607. texture._compression = compression;
  14608. texture.type = type;
  14609. if (!this._doNotHandleContextLost) {
  14610. texture._bufferView = data;
  14611. }
  14612. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14613. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14614. // Filters
  14615. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14617. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14618. if (generateMipMaps) {
  14619. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14620. }
  14621. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14622. this._internalTexturesCache.push(texture);
  14623. return texture;
  14624. };
  14625. /** @hidden */
  14626. Engine.prototype._unpackFlipY = function (value) {
  14627. if (this._unpackFlipYCached !== value) {
  14628. this._unpackFlipYCached = value;
  14629. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14630. }
  14631. };
  14632. /** @hidden */
  14633. Engine.prototype._getUnpackAlignement = function () {
  14634. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14635. };
  14636. /**
  14637. * Creates a dynamic texture
  14638. * @param width defines the width of the texture
  14639. * @param height defines the height of the texture
  14640. * @param generateMipMaps defines if the engine should generate the mip levels
  14641. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14642. * @returns the dynamic texture inside an InternalTexture
  14643. */
  14644. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14645. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14646. texture.baseWidth = width;
  14647. texture.baseHeight = height;
  14648. if (generateMipMaps) {
  14649. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14650. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14651. }
  14652. // this.resetTextureCache();
  14653. texture.width = width;
  14654. texture.height = height;
  14655. texture.isReady = false;
  14656. texture.generateMipMaps = generateMipMaps;
  14657. texture.samplingMode = samplingMode;
  14658. this.updateTextureSamplingMode(samplingMode, texture);
  14659. this._internalTexturesCache.push(texture);
  14660. return texture;
  14661. };
  14662. /**
  14663. * Update the sampling mode of a given texture
  14664. * @param samplingMode defines the required sampling mode
  14665. * @param texture defines the texture to update
  14666. */
  14667. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14668. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14669. if (texture.isCube) {
  14670. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14671. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14672. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14673. }
  14674. else if (texture.is3D) {
  14675. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14676. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14677. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14678. }
  14679. else {
  14680. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14681. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14682. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14683. }
  14684. texture.samplingMode = samplingMode;
  14685. };
  14686. /**
  14687. * Update the content of a dynamic texture
  14688. * @param texture defines the texture to update
  14689. * @param canvas defines the canvas containing the source
  14690. * @param invertY defines if data must be stored with Y axis inverted
  14691. * @param premulAlpha defines if alpha is stored as premultiplied
  14692. * @param format defines the format of the data
  14693. */
  14694. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14695. if (premulAlpha === void 0) { premulAlpha = false; }
  14696. if (!texture) {
  14697. return;
  14698. }
  14699. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14700. this._unpackFlipY(invertY);
  14701. if (premulAlpha) {
  14702. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14703. }
  14704. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14705. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14706. if (texture.generateMipMaps) {
  14707. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14708. }
  14709. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14710. if (premulAlpha) {
  14711. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14712. }
  14713. texture.isReady = true;
  14714. };
  14715. /**
  14716. * Update a video texture
  14717. * @param texture defines the texture to update
  14718. * @param video defines the video element to use
  14719. * @param invertY defines if data must be stored with Y axis inverted
  14720. */
  14721. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14722. if (!texture || texture._isDisabled) {
  14723. return;
  14724. }
  14725. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14726. this._unpackFlipY(!invertY); // Video are upside down by default
  14727. try {
  14728. // Testing video texture support
  14729. if (this._videoTextureSupported === undefined) {
  14730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14731. if (this._gl.getError() !== 0) {
  14732. this._videoTextureSupported = false;
  14733. }
  14734. else {
  14735. this._videoTextureSupported = true;
  14736. }
  14737. }
  14738. // Copy video through the current working canvas if video texture is not supported
  14739. if (!this._videoTextureSupported) {
  14740. if (!texture._workingCanvas) {
  14741. texture._workingCanvas = document.createElement("canvas");
  14742. var context = texture._workingCanvas.getContext("2d");
  14743. if (!context) {
  14744. throw new Error("Unable to get 2d context");
  14745. }
  14746. texture._workingContext = context;
  14747. texture._workingCanvas.width = texture.width;
  14748. texture._workingCanvas.height = texture.height;
  14749. }
  14750. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14751. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14752. }
  14753. else {
  14754. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14755. }
  14756. if (texture.generateMipMaps) {
  14757. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14758. }
  14759. if (!wasPreviouslyBound) {
  14760. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14761. }
  14762. // this.resetTextureCache();
  14763. texture.isReady = true;
  14764. }
  14765. catch (ex) {
  14766. // Something unexpected
  14767. // Let's disable the texture
  14768. texture._isDisabled = true;
  14769. }
  14770. };
  14771. /**
  14772. * Updates a depth texture Comparison Mode and Function.
  14773. * If the comparison Function is equal to 0, the mode will be set to none.
  14774. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14775. * @param texture The texture to set the comparison function for
  14776. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14777. */
  14778. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14779. if (this.webGLVersion === 1) {
  14780. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14781. return;
  14782. }
  14783. var gl = this._gl;
  14784. if (texture.isCube) {
  14785. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14786. if (comparisonFunction === 0) {
  14787. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14789. }
  14790. else {
  14791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14795. }
  14796. else {
  14797. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14798. if (comparisonFunction === 0) {
  14799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14801. }
  14802. else {
  14803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14804. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14805. }
  14806. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14807. }
  14808. texture._comparisonFunction = comparisonFunction;
  14809. };
  14810. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14811. var width = size.width || size;
  14812. var height = size.height || size;
  14813. internalTexture.baseWidth = width;
  14814. internalTexture.baseHeight = height;
  14815. internalTexture.width = width;
  14816. internalTexture.height = height;
  14817. internalTexture.isReady = true;
  14818. internalTexture.samples = 1;
  14819. internalTexture.generateMipMaps = false;
  14820. internalTexture._generateDepthBuffer = true;
  14821. internalTexture._generateStencilBuffer = generateStencil;
  14822. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14823. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14824. internalTexture._comparisonFunction = comparisonFunction;
  14825. var gl = this._gl;
  14826. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14827. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14828. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14829. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14830. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14831. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14832. if (comparisonFunction === 0) {
  14833. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14834. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14835. }
  14836. else {
  14837. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14838. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14839. }
  14840. };
  14841. /**
  14842. * Creates a depth stencil texture.
  14843. * This is only available in WebGL 2 or with the depth texture extension available.
  14844. * @param size The size of face edge in the texture.
  14845. * @param options The options defining the texture.
  14846. * @returns The texture
  14847. */
  14848. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14849. if (options.isCube) {
  14850. var width = size.width || size;
  14851. return this._createDepthStencilCubeTexture(width, options);
  14852. }
  14853. else {
  14854. return this._createDepthStencilTexture(size, options);
  14855. }
  14856. };
  14857. /**
  14858. * Creates a depth stencil texture.
  14859. * This is only available in WebGL 2 or with the depth texture extension available.
  14860. * @param size The size of face edge in the texture.
  14861. * @param options The options defining the texture.
  14862. * @returns The texture
  14863. */
  14864. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14865. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14866. if (!this._caps.depthTextureExtension) {
  14867. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14868. return internalTexture;
  14869. }
  14870. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14871. var gl = this._gl;
  14872. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14873. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14874. if (this.webGLVersion > 1) {
  14875. if (internalOptions.generateStencil) {
  14876. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14877. }
  14878. else {
  14879. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14880. }
  14881. }
  14882. else {
  14883. if (internalOptions.generateStencil) {
  14884. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14885. }
  14886. else {
  14887. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14888. }
  14889. }
  14890. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14891. return internalTexture;
  14892. };
  14893. /**
  14894. * Creates a depth stencil cube texture.
  14895. * This is only available in WebGL 2.
  14896. * @param size The size of face edge in the cube texture.
  14897. * @param options The options defining the cube texture.
  14898. * @returns The cube texture
  14899. */
  14900. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14901. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14902. internalTexture.isCube = true;
  14903. if (this.webGLVersion === 1) {
  14904. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14905. return internalTexture;
  14906. }
  14907. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14908. var gl = this._gl;
  14909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14910. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14911. // Create the depth/stencil buffer
  14912. for (var face = 0; face < 6; face++) {
  14913. if (internalOptions.generateStencil) {
  14914. 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);
  14915. }
  14916. else {
  14917. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14918. }
  14919. }
  14920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14921. return internalTexture;
  14922. };
  14923. /**
  14924. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14925. * @param renderTarget The render target to set the frame buffer for
  14926. */
  14927. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14928. // Create the framebuffer
  14929. var internalTexture = renderTarget.getInternalTexture();
  14930. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14931. return;
  14932. }
  14933. var gl = this._gl;
  14934. var depthStencilTexture = renderTarget.depthStencilTexture;
  14935. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14936. if (depthStencilTexture.isCube) {
  14937. if (depthStencilTexture._generateStencilBuffer) {
  14938. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14939. }
  14940. else {
  14941. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14942. }
  14943. }
  14944. else {
  14945. if (depthStencilTexture._generateStencilBuffer) {
  14946. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14947. }
  14948. else {
  14949. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14950. }
  14951. }
  14952. this.bindUnboundFramebuffer(null);
  14953. };
  14954. /**
  14955. * Creates a new render target texture
  14956. * @param size defines the size of the texture
  14957. * @param options defines the options used to create the texture
  14958. * @returns a new render target texture stored in an InternalTexture
  14959. */
  14960. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14961. var fullOptions = new RenderTargetCreationOptions();
  14962. if (options !== undefined && typeof options === "object") {
  14963. fullOptions.generateMipMaps = options.generateMipMaps;
  14964. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14965. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14966. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14967. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14968. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14969. }
  14970. else {
  14971. fullOptions.generateMipMaps = options;
  14972. fullOptions.generateDepthBuffer = true;
  14973. fullOptions.generateStencilBuffer = false;
  14974. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14975. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  14976. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14977. }
  14978. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14979. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14980. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14981. }
  14982. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14983. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14984. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14985. }
  14986. var gl = this._gl;
  14987. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14988. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14989. var width = size.width || size;
  14990. var height = size.height || size;
  14991. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  14992. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14993. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14994. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14995. }
  14996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15000. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15001. // Create the framebuffer
  15002. var currentFrameBuffer = this._currentFramebuffer;
  15003. var framebuffer = gl.createFramebuffer();
  15004. this.bindUnboundFramebuffer(framebuffer);
  15005. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15006. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15007. if (fullOptions.generateMipMaps) {
  15008. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15009. }
  15010. // Unbind
  15011. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15012. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15013. this.bindUnboundFramebuffer(currentFrameBuffer);
  15014. texture._framebuffer = framebuffer;
  15015. texture.baseWidth = width;
  15016. texture.baseHeight = height;
  15017. texture.width = width;
  15018. texture.height = height;
  15019. texture.isReady = true;
  15020. texture.samples = 1;
  15021. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15022. texture.samplingMode = fullOptions.samplingMode;
  15023. texture.type = fullOptions.type;
  15024. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15025. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15026. // this.resetTextureCache();
  15027. this._internalTexturesCache.push(texture);
  15028. return texture;
  15029. };
  15030. /**
  15031. * Create a multi render target texture
  15032. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15033. * @param size defines the size of the texture
  15034. * @param options defines the creation options
  15035. * @returns the cube texture as an InternalTexture
  15036. */
  15037. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15038. var generateMipMaps = false;
  15039. var generateDepthBuffer = true;
  15040. var generateStencilBuffer = false;
  15041. var generateDepthTexture = false;
  15042. var textureCount = 1;
  15043. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15044. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15045. var types = new Array();
  15046. var samplingModes = new Array();
  15047. if (options !== undefined) {
  15048. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15049. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15050. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15051. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15052. textureCount = options.textureCount || 1;
  15053. if (options.types) {
  15054. types = options.types;
  15055. }
  15056. if (options.samplingModes) {
  15057. samplingModes = options.samplingModes;
  15058. }
  15059. }
  15060. var gl = this._gl;
  15061. // Create the framebuffer
  15062. var framebuffer = gl.createFramebuffer();
  15063. this.bindUnboundFramebuffer(framebuffer);
  15064. var width = size.width || size;
  15065. var height = size.height || size;
  15066. var textures = [];
  15067. var attachments = [];
  15068. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15069. for (var i = 0; i < textureCount; i++) {
  15070. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15071. var type = types[i] || defaultType;
  15072. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15073. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15074. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15075. }
  15076. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15077. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15078. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15079. }
  15080. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15081. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15082. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15083. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15084. }
  15085. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15086. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15087. textures.push(texture);
  15088. attachments.push(attachment);
  15089. gl.activeTexture(gl["TEXTURE" + i]);
  15090. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15093. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15094. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15095. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15096. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15097. if (generateMipMaps) {
  15098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15099. }
  15100. // Unbind
  15101. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15102. texture._framebuffer = framebuffer;
  15103. texture._depthStencilBuffer = depthStencilBuffer;
  15104. texture.baseWidth = width;
  15105. texture.baseHeight = height;
  15106. texture.width = width;
  15107. texture.height = height;
  15108. texture.isReady = true;
  15109. texture.samples = 1;
  15110. texture.generateMipMaps = generateMipMaps;
  15111. texture.samplingMode = samplingMode;
  15112. texture.type = type;
  15113. texture._generateDepthBuffer = generateDepthBuffer;
  15114. texture._generateStencilBuffer = generateStencilBuffer;
  15115. texture._attachments = attachments;
  15116. this._internalTexturesCache.push(texture);
  15117. }
  15118. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15119. // Depth texture
  15120. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15121. gl.activeTexture(gl.TEXTURE0);
  15122. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15127. 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);
  15128. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15129. depthTexture._framebuffer = framebuffer;
  15130. depthTexture.baseWidth = width;
  15131. depthTexture.baseHeight = height;
  15132. depthTexture.width = width;
  15133. depthTexture.height = height;
  15134. depthTexture.isReady = true;
  15135. depthTexture.samples = 1;
  15136. depthTexture.generateMipMaps = generateMipMaps;
  15137. depthTexture.samplingMode = gl.NEAREST;
  15138. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15139. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15140. textures.push(depthTexture);
  15141. this._internalTexturesCache.push(depthTexture);
  15142. }
  15143. gl.drawBuffers(attachments);
  15144. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15145. this.bindUnboundFramebuffer(null);
  15146. this.resetTextureCache();
  15147. return textures;
  15148. };
  15149. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15150. if (samples === void 0) { samples = 1; }
  15151. var depthStencilBuffer = null;
  15152. var gl = this._gl;
  15153. // Create the depth/stencil buffer
  15154. if (generateStencilBuffer) {
  15155. depthStencilBuffer = gl.createRenderbuffer();
  15156. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15157. if (samples > 1) {
  15158. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15159. }
  15160. else {
  15161. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15162. }
  15163. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15164. }
  15165. else if (generateDepthBuffer) {
  15166. depthStencilBuffer = gl.createRenderbuffer();
  15167. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15168. if (samples > 1) {
  15169. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15170. }
  15171. else {
  15172. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15173. }
  15174. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15175. }
  15176. return depthStencilBuffer;
  15177. };
  15178. /**
  15179. * Updates the sample count of a render target texture
  15180. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15181. * @param texture defines the texture to update
  15182. * @param samples defines the sample count to set
  15183. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15184. */
  15185. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15186. if (this.webGLVersion < 2 || !texture) {
  15187. return 1;
  15188. }
  15189. if (texture.samples === samples) {
  15190. return samples;
  15191. }
  15192. var gl = this._gl;
  15193. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15194. // Dispose previous render buffers
  15195. if (texture._depthStencilBuffer) {
  15196. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15197. texture._depthStencilBuffer = null;
  15198. }
  15199. if (texture._MSAAFramebuffer) {
  15200. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15201. texture._MSAAFramebuffer = null;
  15202. }
  15203. if (texture._MSAARenderBuffer) {
  15204. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15205. texture._MSAARenderBuffer = null;
  15206. }
  15207. if (samples > 1) {
  15208. var framebuffer = gl.createFramebuffer();
  15209. if (!framebuffer) {
  15210. throw new Error("Unable to create multi sampled framebuffer");
  15211. }
  15212. texture._MSAAFramebuffer = framebuffer;
  15213. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15214. var colorRenderbuffer = gl.createRenderbuffer();
  15215. if (!colorRenderbuffer) {
  15216. throw new Error("Unable to create multi sampled framebuffer");
  15217. }
  15218. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15219. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15220. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15221. texture._MSAARenderBuffer = colorRenderbuffer;
  15222. }
  15223. else {
  15224. this.bindUnboundFramebuffer(texture._framebuffer);
  15225. }
  15226. texture.samples = samples;
  15227. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15228. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15229. this.bindUnboundFramebuffer(null);
  15230. return samples;
  15231. };
  15232. /**
  15233. * Update the sample count for a given multiple render target texture
  15234. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15235. * @param textures defines the textures to update
  15236. * @param samples defines the sample count to set
  15237. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15238. */
  15239. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15240. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15241. return 1;
  15242. }
  15243. if (textures[0].samples === samples) {
  15244. return samples;
  15245. }
  15246. var gl = this._gl;
  15247. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15248. // Dispose previous render buffers
  15249. if (textures[0]._depthStencilBuffer) {
  15250. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15251. textures[0]._depthStencilBuffer = null;
  15252. }
  15253. if (textures[0]._MSAAFramebuffer) {
  15254. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15255. textures[0]._MSAAFramebuffer = null;
  15256. }
  15257. for (var i = 0; i < textures.length; i++) {
  15258. if (textures[i]._MSAARenderBuffer) {
  15259. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15260. textures[i]._MSAARenderBuffer = null;
  15261. }
  15262. }
  15263. if (samples > 1) {
  15264. var framebuffer = gl.createFramebuffer();
  15265. if (!framebuffer) {
  15266. throw new Error("Unable to create multi sampled framebuffer");
  15267. }
  15268. this.bindUnboundFramebuffer(framebuffer);
  15269. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15270. var attachments = [];
  15271. for (var i = 0; i < textures.length; i++) {
  15272. var texture = textures[i];
  15273. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15274. var colorRenderbuffer = gl.createRenderbuffer();
  15275. if (!colorRenderbuffer) {
  15276. throw new Error("Unable to create multi sampled framebuffer");
  15277. }
  15278. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15279. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15280. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15281. texture._MSAAFramebuffer = framebuffer;
  15282. texture._MSAARenderBuffer = colorRenderbuffer;
  15283. texture.samples = samples;
  15284. texture._depthStencilBuffer = depthStencilBuffer;
  15285. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15286. attachments.push(attachment);
  15287. }
  15288. gl.drawBuffers(attachments);
  15289. }
  15290. else {
  15291. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15292. }
  15293. this.bindUnboundFramebuffer(null);
  15294. return samples;
  15295. };
  15296. /** @hidden */
  15297. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15298. if (faceIndex === void 0) { faceIndex = 0; }
  15299. if (lod === void 0) { lod = 0; }
  15300. var gl = this._gl;
  15301. var target = gl.TEXTURE_2D;
  15302. if (texture.isCube) {
  15303. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15304. }
  15305. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15306. };
  15307. /** @hidden */
  15308. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15309. if (faceIndex === void 0) { faceIndex = 0; }
  15310. if (lod === void 0) { lod = 0; }
  15311. var gl = this._gl;
  15312. var textureType = this._getWebGLTextureType(texture.type);
  15313. var format = this._getInternalFormat(texture.format);
  15314. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15315. this._unpackFlipY(texture.invertY);
  15316. var target = gl.TEXTURE_2D;
  15317. if (texture.isCube) {
  15318. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15319. }
  15320. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15321. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15322. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15323. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15324. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15325. };
  15326. /** @hidden */
  15327. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15328. if (faceIndex === void 0) { faceIndex = 0; }
  15329. if (lod === void 0) { lod = 0; }
  15330. var gl = this._gl;
  15331. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15332. this._bindTextureDirectly(bindTarget, texture, true);
  15333. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15334. this._bindTextureDirectly(bindTarget, null, true);
  15335. };
  15336. /** @hidden */
  15337. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15338. if (faceIndex === void 0) { faceIndex = 0; }
  15339. if (lod === void 0) { lod = 0; }
  15340. var gl = this._gl;
  15341. var textureType = this._getWebGLTextureType(texture.type);
  15342. var format = this._getInternalFormat(texture.format);
  15343. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15344. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15345. this._bindTextureDirectly(bindTarget, texture, true);
  15346. this._unpackFlipY(texture.invertY);
  15347. var target = gl.TEXTURE_2D;
  15348. if (texture.isCube) {
  15349. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15350. }
  15351. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15352. this._bindTextureDirectly(bindTarget, null, true);
  15353. };
  15354. /**
  15355. * Creates a new render target cube texture
  15356. * @param size defines the size of the texture
  15357. * @param options defines the options used to create the texture
  15358. * @returns a new render target cube texture stored in an InternalTexture
  15359. */
  15360. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15361. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15362. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15363. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15364. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15365. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15366. }
  15367. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15368. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15369. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15370. }
  15371. var gl = this._gl;
  15372. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15373. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15374. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15375. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15376. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15377. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15378. }
  15379. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15380. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15383. for (var face = 0; face < 6; face++) {
  15384. 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);
  15385. }
  15386. // Create the framebuffer
  15387. var framebuffer = gl.createFramebuffer();
  15388. this.bindUnboundFramebuffer(framebuffer);
  15389. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15390. // MipMaps
  15391. if (fullOptions.generateMipMaps) {
  15392. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15393. }
  15394. // Unbind
  15395. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15396. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15397. this.bindUnboundFramebuffer(null);
  15398. texture._framebuffer = framebuffer;
  15399. texture.width = size;
  15400. texture.height = size;
  15401. texture.isReady = true;
  15402. texture.isCube = true;
  15403. texture.samples = 1;
  15404. texture.generateMipMaps = fullOptions.generateMipMaps;
  15405. texture.samplingMode = fullOptions.samplingMode;
  15406. texture.type = fullOptions.type;
  15407. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15408. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15409. this._internalTexturesCache.push(texture);
  15410. return texture;
  15411. };
  15412. /**
  15413. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15414. * @param rootUrl defines the url where the file to load is located
  15415. * @param scene defines the current scene
  15416. * @param lodScale defines scale to apply to the mip map selection
  15417. * @param lodOffset defines offset to apply to the mip map selection
  15418. * @param onLoad defines an optional callback raised when the texture is loaded
  15419. * @param onError defines an optional callback raised if there is an issue to load the texture
  15420. * @param format defines the format of the data
  15421. * @param forcedExtension defines the extension to use to pick the right loader
  15422. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15423. * @returns the cube texture as an InternalTexture
  15424. */
  15425. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15426. var _this = this;
  15427. if (onLoad === void 0) { onLoad = null; }
  15428. if (onError === void 0) { onError = null; }
  15429. if (forcedExtension === void 0) { forcedExtension = null; }
  15430. if (createPolynomials === void 0) { createPolynomials = true; }
  15431. var callback = function (loadData) {
  15432. if (!loadData) {
  15433. if (onLoad) {
  15434. onLoad(null);
  15435. }
  15436. return;
  15437. }
  15438. var texture = loadData.texture;
  15439. if (!createPolynomials) {
  15440. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15441. }
  15442. else if (loadData.info.sphericalPolynomial) {
  15443. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15444. }
  15445. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15446. if (_this._caps.textureLOD) {
  15447. // Do not add extra process if texture lod is supported.
  15448. if (onLoad) {
  15449. onLoad(texture);
  15450. }
  15451. return;
  15452. }
  15453. var mipSlices = 3;
  15454. var gl = _this._gl;
  15455. var width = loadData.width;
  15456. if (!width) {
  15457. return;
  15458. }
  15459. var textures = [];
  15460. for (var i = 0; i < mipSlices; i++) {
  15461. //compute LOD from even spacing in smoothness (matching shader calculation)
  15462. var smoothness = i / (mipSlices - 1);
  15463. var roughness = 1 - smoothness;
  15464. var minLODIndex = lodOffset; // roughness = 0
  15465. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15466. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15467. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15468. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15469. glTextureFromLod.type = texture.type;
  15470. glTextureFromLod.format = texture.format;
  15471. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15472. glTextureFromLod.height = glTextureFromLod.width;
  15473. glTextureFromLod.isCube = true;
  15474. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15477. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15479. if (loadData.isDDS) {
  15480. var info = loadData.info;
  15481. var data = loadData.data;
  15482. _this._unpackFlipY(info.isCompressed);
  15483. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15484. }
  15485. else {
  15486. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15487. }
  15488. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15489. // Wrap in a base texture for easy binding.
  15490. var lodTexture = new BABYLON.BaseTexture(scene);
  15491. lodTexture.isCube = true;
  15492. lodTexture._texture = glTextureFromLod;
  15493. glTextureFromLod.isReady = true;
  15494. textures.push(lodTexture);
  15495. }
  15496. texture._lodTextureHigh = textures[2];
  15497. texture._lodTextureMid = textures[1];
  15498. texture._lodTextureLow = textures[0];
  15499. if (onLoad) {
  15500. onLoad(texture);
  15501. }
  15502. };
  15503. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15504. };
  15505. /**
  15506. * Creates a cube texture
  15507. * @param rootUrl defines the url where the files to load is located
  15508. * @param scene defines the current scene
  15509. * @param files defines the list of files to load (1 per face)
  15510. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15511. * @param onLoad defines an optional callback raised when the texture is loaded
  15512. * @param onError defines an optional callback raised if there is an issue to load the texture
  15513. * @param format defines the format of the data
  15514. * @param forcedExtension defines the extension to use to pick the right loader
  15515. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15516. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15517. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15518. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15519. * @returns the cube texture as an InternalTexture
  15520. */
  15521. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15522. var _this = this;
  15523. if (onLoad === void 0) { onLoad = null; }
  15524. if (onError === void 0) { onError = null; }
  15525. if (forcedExtension === void 0) { forcedExtension = null; }
  15526. if (createPolynomials === void 0) { createPolynomials = false; }
  15527. if (lodScale === void 0) { lodScale = 0; }
  15528. if (lodOffset === void 0) { lodOffset = 0; }
  15529. if (fallback === void 0) { fallback = null; }
  15530. var gl = this._gl;
  15531. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15532. texture.isCube = true;
  15533. texture.url = rootUrl;
  15534. texture.generateMipMaps = !noMipmap;
  15535. texture._lodGenerationScale = lodScale;
  15536. texture._lodGenerationOffset = lodOffset;
  15537. if (!this._doNotHandleContextLost) {
  15538. texture._extension = forcedExtension;
  15539. texture._files = files;
  15540. }
  15541. var lastDot = rootUrl.lastIndexOf('.');
  15542. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15543. var loader = null;
  15544. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15545. var availableLoader = _a[_i];
  15546. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15547. loader = availableLoader;
  15548. break;
  15549. }
  15550. }
  15551. var onInternalError = function (request, exception) {
  15552. if (loader) {
  15553. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15554. if (fallbackUrl) {
  15555. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15556. }
  15557. }
  15558. if (onError && request) {
  15559. onError(request.status + " " + request.statusText, exception);
  15560. }
  15561. };
  15562. if (loader) {
  15563. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15564. var onloaddata = function (data) {
  15565. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15566. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15567. };
  15568. if (files && files.length === 6) {
  15569. if (loader.supportCascades) {
  15570. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15571. }
  15572. else if (onError) {
  15573. onError("Textures type does not support cascades.");
  15574. }
  15575. }
  15576. else {
  15577. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15578. }
  15579. }
  15580. else {
  15581. if (!files) {
  15582. throw new Error("Cannot load cubemap because files were not defined");
  15583. }
  15584. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15585. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15586. var height = width;
  15587. _this._prepareWorkingCanvas();
  15588. if (!_this._workingCanvas || !_this._workingContext) {
  15589. return;
  15590. }
  15591. _this._workingCanvas.width = width;
  15592. _this._workingCanvas.height = height;
  15593. var faces = [
  15594. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15595. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15596. ];
  15597. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15598. _this._unpackFlipY(false);
  15599. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15600. for (var index = 0; index < faces.length; index++) {
  15601. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15602. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15603. }
  15604. if (!noMipmap) {
  15605. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15606. }
  15607. _this._setCubeMapTextureParams(!noMipmap);
  15608. texture.width = width;
  15609. texture.height = height;
  15610. texture.isReady = true;
  15611. if (format) {
  15612. texture.format = format;
  15613. }
  15614. texture.onLoadedObservable.notifyObservers(texture);
  15615. texture.onLoadedObservable.clear();
  15616. if (onLoad) {
  15617. onLoad();
  15618. }
  15619. }, files, onError);
  15620. }
  15621. this._internalTexturesCache.push(texture);
  15622. return texture;
  15623. };
  15624. /**
  15625. * @hidden
  15626. */
  15627. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15628. var gl = this._gl;
  15629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15630. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15631. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15632. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15633. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15634. // this.resetTextureCache();
  15635. };
  15636. /**
  15637. * Update a raw cube texture
  15638. * @param texture defines the texture to udpdate
  15639. * @param data defines the data to store
  15640. * @param format defines the data format
  15641. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15642. * @param invertY defines if data must be stored with Y axis inverted
  15643. * @param compression defines the compression used (null by default)
  15644. * @param level defines which level of the texture to update
  15645. */
  15646. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15647. if (compression === void 0) { compression = null; }
  15648. if (level === void 0) { level = 0; }
  15649. texture._bufferViewArray = data;
  15650. texture.format = format;
  15651. texture.type = type;
  15652. texture.invertY = invertY;
  15653. texture._compression = compression;
  15654. var gl = this._gl;
  15655. var textureType = this._getWebGLTextureType(type);
  15656. var internalFormat = this._getInternalFormat(format);
  15657. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15658. var needConversion = false;
  15659. if (internalFormat === gl.RGB) {
  15660. internalFormat = gl.RGBA;
  15661. needConversion = true;
  15662. }
  15663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15665. if (texture.width % 4 !== 0) {
  15666. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15667. }
  15668. // Data are known to be in +X +Y +Z -X -Y -Z
  15669. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15670. var faceData = data[faceIndex];
  15671. if (compression) {
  15672. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15673. }
  15674. else {
  15675. if (needConversion) {
  15676. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15677. }
  15678. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15679. }
  15680. }
  15681. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15682. if (isPot && texture.generateMipMaps && level === 0) {
  15683. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15684. }
  15685. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15686. // this.resetTextureCache();
  15687. texture.isReady = true;
  15688. };
  15689. /**
  15690. * Creates a new raw cube texture
  15691. * @param data defines the array of data to use to create each face
  15692. * @param size defines the size of the textures
  15693. * @param format defines the format of the data
  15694. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15695. * @param generateMipMaps defines if the engine should generate the mip levels
  15696. * @param invertY defines if data must be stored with Y axis inverted
  15697. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15698. * @param compression defines the compression used (null by default)
  15699. * @returns the cube texture as an InternalTexture
  15700. */
  15701. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15702. if (compression === void 0) { compression = null; }
  15703. var gl = this._gl;
  15704. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15705. texture.isCube = true;
  15706. texture.format = format;
  15707. texture.type = type;
  15708. if (!this._doNotHandleContextLost) {
  15709. texture._bufferViewArray = data;
  15710. }
  15711. var textureType = this._getWebGLTextureType(type);
  15712. var internalFormat = this._getInternalFormat(format);
  15713. if (internalFormat === gl.RGB) {
  15714. internalFormat = gl.RGBA;
  15715. }
  15716. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15717. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15718. generateMipMaps = false;
  15719. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15720. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15721. }
  15722. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15723. generateMipMaps = false;
  15724. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15725. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15726. }
  15727. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15728. generateMipMaps = false;
  15729. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15730. }
  15731. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15732. generateMipMaps = false;
  15733. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15734. }
  15735. var width = size;
  15736. var height = width;
  15737. texture.width = width;
  15738. texture.height = height;
  15739. // Double check on POT to generate Mips.
  15740. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15741. if (!isPot) {
  15742. generateMipMaps = false;
  15743. }
  15744. // Upload data if needed. The texture won't be ready until then.
  15745. if (data) {
  15746. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15747. }
  15748. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15749. // Filters
  15750. if (data && generateMipMaps) {
  15751. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15752. }
  15753. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15755. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15758. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15759. texture.generateMipMaps = generateMipMaps;
  15760. return texture;
  15761. };
  15762. /**
  15763. * Creates a new raw cube texture from a specified url
  15764. * @param url defines the url where the data is located
  15765. * @param scene defines the current scene
  15766. * @param size defines the size of the textures
  15767. * @param format defines the format of the data
  15768. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15769. * @param noMipmap defines if the engine should avoid generating the mip levels
  15770. * @param callback defines a callback used to extract texture data from loaded data
  15771. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15772. * @param onLoad defines a callback called when texture is loaded
  15773. * @param onError defines a callback called if there is an error
  15774. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15775. * @param invertY defines if data must be stored with Y axis inverted
  15776. * @returns the cube texture as an InternalTexture
  15777. */
  15778. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15779. var _this = this;
  15780. if (onLoad === void 0) { onLoad = null; }
  15781. if (onError === void 0) { onError = null; }
  15782. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15783. if (invertY === void 0) { invertY = false; }
  15784. var gl = this._gl;
  15785. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15786. scene._addPendingData(texture);
  15787. texture.url = url;
  15788. this._internalTexturesCache.push(texture);
  15789. var onerror = function (request, exception) {
  15790. scene._removePendingData(texture);
  15791. if (onError && request) {
  15792. onError(request.status + " " + request.statusText, exception);
  15793. }
  15794. };
  15795. var internalCallback = function (data) {
  15796. var width = texture.width;
  15797. var faceDataArrays = callback(data);
  15798. if (!faceDataArrays) {
  15799. return;
  15800. }
  15801. if (mipmapGenerator) {
  15802. var textureType = _this._getWebGLTextureType(type);
  15803. var internalFormat = _this._getInternalFormat(format);
  15804. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15805. var needConversion = false;
  15806. if (internalFormat === gl.RGB) {
  15807. internalFormat = gl.RGBA;
  15808. needConversion = true;
  15809. }
  15810. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15811. _this._unpackFlipY(false);
  15812. var mipData = mipmapGenerator(faceDataArrays);
  15813. for (var level = 0; level < mipData.length; level++) {
  15814. var mipSize = width >> level;
  15815. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15816. var mipFaceData = mipData[level][faceIndex];
  15817. if (needConversion) {
  15818. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15819. }
  15820. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15821. }
  15822. }
  15823. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15824. }
  15825. else {
  15826. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15827. }
  15828. texture.isReady = true;
  15829. // this.resetTextureCache();
  15830. scene._removePendingData(texture);
  15831. if (onLoad) {
  15832. onLoad();
  15833. }
  15834. };
  15835. this._loadFile(url, function (data) {
  15836. internalCallback(data);
  15837. }, undefined, scene.database, true, onerror);
  15838. return texture;
  15839. };
  15840. ;
  15841. /**
  15842. * Update a raw 3D texture
  15843. * @param texture defines the texture to update
  15844. * @param data defines the data to store
  15845. * @param format defines the data format
  15846. * @param invertY defines if data must be stored with Y axis inverted
  15847. * @param compression defines the used compression (can be null)
  15848. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15849. */
  15850. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15851. if (compression === void 0) { compression = null; }
  15852. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15853. var internalType = this._getWebGLTextureType(textureType);
  15854. var internalFormat = this._getInternalFormat(format);
  15855. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15856. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15857. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15858. if (!this._doNotHandleContextLost) {
  15859. texture._bufferView = data;
  15860. texture.format = format;
  15861. texture.invertY = invertY;
  15862. texture._compression = compression;
  15863. }
  15864. if (texture.width % 4 !== 0) {
  15865. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15866. }
  15867. if (compression && data) {
  15868. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15869. }
  15870. else {
  15871. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15872. }
  15873. if (texture.generateMipMaps) {
  15874. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15875. }
  15876. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15877. // this.resetTextureCache();
  15878. texture.isReady = true;
  15879. };
  15880. /**
  15881. * Creates a new raw 3D texture
  15882. * @param data defines the data used to create the texture
  15883. * @param width defines the width of the texture
  15884. * @param height defines the height of the texture
  15885. * @param depth defines the depth of the texture
  15886. * @param format defines the format of the texture
  15887. * @param generateMipMaps defines if the engine must generate mip levels
  15888. * @param invertY defines if data must be stored with Y axis inverted
  15889. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15890. * @param compression defines the compressed used (can be null)
  15891. * @param textureType defines the compressed used (can be null)
  15892. * @returns a new raw 3D texture (stored in an InternalTexture)
  15893. */
  15894. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15895. if (compression === void 0) { compression = null; }
  15896. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15897. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15898. texture.baseWidth = width;
  15899. texture.baseHeight = height;
  15900. texture.baseDepth = depth;
  15901. texture.width = width;
  15902. texture.height = height;
  15903. texture.depth = depth;
  15904. texture.format = format;
  15905. texture.type = textureType;
  15906. texture.generateMipMaps = generateMipMaps;
  15907. texture.samplingMode = samplingMode;
  15908. texture.is3D = true;
  15909. if (!this._doNotHandleContextLost) {
  15910. texture._bufferView = data;
  15911. }
  15912. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  15913. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15914. // Filters
  15915. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15916. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15917. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15918. if (generateMipMaps) {
  15919. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15920. }
  15921. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15922. this._internalTexturesCache.push(texture);
  15923. return texture;
  15924. };
  15925. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15926. var gl = this._gl;
  15927. if (!gl) {
  15928. return;
  15929. }
  15930. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  15931. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15932. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15933. if (!noMipmap && !isCompressed) {
  15934. gl.generateMipmap(gl.TEXTURE_2D);
  15935. }
  15936. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15937. // this.resetTextureCache();
  15938. if (scene) {
  15939. scene._removePendingData(texture);
  15940. }
  15941. texture.onLoadedObservable.notifyObservers(texture);
  15942. texture.onLoadedObservable.clear();
  15943. };
  15944. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15945. var _this = this;
  15946. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15947. var maxTextureSize = this.getCaps().maxTextureSize;
  15948. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  15949. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  15950. var gl = this._gl;
  15951. if (!gl) {
  15952. return;
  15953. }
  15954. if (!texture._webGLTexture) {
  15955. // this.resetTextureCache();
  15956. if (scene) {
  15957. scene._removePendingData(texture);
  15958. }
  15959. return;
  15960. }
  15961. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15962. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15963. texture.baseWidth = width;
  15964. texture.baseHeight = height;
  15965. texture.width = potWidth;
  15966. texture.height = potHeight;
  15967. texture.isReady = true;
  15968. if (processFunction(potWidth, potHeight, function () {
  15969. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15970. })) {
  15971. // Returning as texture needs extra async steps
  15972. return;
  15973. }
  15974. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15975. };
  15976. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15977. // Create new RGBA data container.
  15978. var rgbaData;
  15979. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15980. rgbaData = new Float32Array(width * height * 4);
  15981. }
  15982. else {
  15983. rgbaData = new Uint32Array(width * height * 4);
  15984. }
  15985. // Convert each pixel.
  15986. for (var x = 0; x < width; x++) {
  15987. for (var y = 0; y < height; y++) {
  15988. var index = (y * width + x) * 3;
  15989. var newIndex = (y * width + x) * 4;
  15990. // Map Old Value to new value.
  15991. rgbaData[newIndex + 0] = rgbData[index + 0];
  15992. rgbaData[newIndex + 1] = rgbData[index + 1];
  15993. rgbaData[newIndex + 2] = rgbData[index + 2];
  15994. // Add fully opaque alpha channel.
  15995. rgbaData[newIndex + 3] = 1;
  15996. }
  15997. }
  15998. return rgbaData;
  15999. };
  16000. /** @hidden */
  16001. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16002. var gl = this._gl;
  16003. if (texture._framebuffer) {
  16004. gl.deleteFramebuffer(texture._framebuffer);
  16005. texture._framebuffer = null;
  16006. }
  16007. if (texture._depthStencilBuffer) {
  16008. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16009. texture._depthStencilBuffer = null;
  16010. }
  16011. if (texture._MSAAFramebuffer) {
  16012. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16013. texture._MSAAFramebuffer = null;
  16014. }
  16015. if (texture._MSAARenderBuffer) {
  16016. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16017. texture._MSAARenderBuffer = null;
  16018. }
  16019. };
  16020. /** @hidden */
  16021. Engine.prototype._releaseTexture = function (texture) {
  16022. var gl = this._gl;
  16023. this._releaseFramebufferObjects(texture);
  16024. gl.deleteTexture(texture._webGLTexture);
  16025. // Unbind channels
  16026. this.unbindAllTextures();
  16027. var index = this._internalTexturesCache.indexOf(texture);
  16028. if (index !== -1) {
  16029. this._internalTexturesCache.splice(index, 1);
  16030. }
  16031. // Integrated fixed lod samplers.
  16032. if (texture._lodTextureHigh) {
  16033. texture._lodTextureHigh.dispose();
  16034. }
  16035. if (texture._lodTextureMid) {
  16036. texture._lodTextureMid.dispose();
  16037. }
  16038. if (texture._lodTextureLow) {
  16039. texture._lodTextureLow.dispose();
  16040. }
  16041. // Set output texture of post process to null if the texture has been released/disposed
  16042. this.scenes.forEach(function (scene) {
  16043. scene.postProcesses.forEach(function (postProcess) {
  16044. if (postProcess._outputTexture == texture) {
  16045. postProcess._outputTexture = null;
  16046. }
  16047. });
  16048. scene.cameras.forEach(function (camera) {
  16049. camera._postProcesses.forEach(function (postProcess) {
  16050. if (postProcess) {
  16051. if (postProcess._outputTexture == texture) {
  16052. postProcess._outputTexture = null;
  16053. }
  16054. }
  16055. });
  16056. });
  16057. });
  16058. };
  16059. Engine.prototype.setProgram = function (program) {
  16060. if (this._currentProgram !== program) {
  16061. this._gl.useProgram(program);
  16062. this._currentProgram = program;
  16063. }
  16064. };
  16065. /**
  16066. * Binds an effect to the webGL context
  16067. * @param effect defines the effect to bind
  16068. */
  16069. Engine.prototype.bindSamplers = function (effect) {
  16070. this.setProgram(effect.getProgram());
  16071. var samplers = effect.getSamplers();
  16072. for (var index = 0; index < samplers.length; index++) {
  16073. var uniform = effect.getUniform(samplers[index]);
  16074. if (uniform) {
  16075. this._boundUniforms[index] = uniform;
  16076. }
  16077. }
  16078. this._currentEffect = null;
  16079. };
  16080. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16081. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16082. return;
  16083. }
  16084. // Remove
  16085. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16086. // Bind last to it
  16087. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16088. // Bind to dummy
  16089. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16090. };
  16091. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16092. if (!internalTexture) {
  16093. return -1;
  16094. }
  16095. internalTexture._initialSlot = channel;
  16096. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16097. if (channel !== internalTexture._designatedSlot) {
  16098. this._textureCollisions.addCount(1, false);
  16099. }
  16100. }
  16101. else {
  16102. if (channel !== internalTexture._designatedSlot) {
  16103. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16104. return internalTexture._designatedSlot;
  16105. }
  16106. else {
  16107. // No slot for this texture, let's pick a new one (if we find a free slot)
  16108. if (this._nextFreeTextureSlots.length) {
  16109. return this._nextFreeTextureSlots[0];
  16110. }
  16111. // We need to recycle the oldest bound texture, sorry.
  16112. this._textureCollisions.addCount(1, false);
  16113. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16114. }
  16115. }
  16116. }
  16117. return channel;
  16118. };
  16119. Engine.prototype._linkTrackers = function (previous, next) {
  16120. previous.next = next;
  16121. next.previous = previous;
  16122. };
  16123. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16124. var currentSlot = internalTexture._designatedSlot;
  16125. if (currentSlot === -1) {
  16126. return -1;
  16127. }
  16128. internalTexture._designatedSlot = -1;
  16129. if (this.disableTextureBindingOptimization) {
  16130. return -1;
  16131. }
  16132. // Remove from bound list
  16133. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16134. // Free the slot
  16135. this._boundTexturesCache[currentSlot] = null;
  16136. this._nextFreeTextureSlots.push(currentSlot);
  16137. return currentSlot;
  16138. };
  16139. Engine.prototype._activateCurrentTexture = function () {
  16140. if (this._currentTextureChannel !== this._activeChannel) {
  16141. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16142. this._currentTextureChannel = this._activeChannel;
  16143. }
  16144. };
  16145. /** @hidden */
  16146. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16147. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16148. if (force === void 0) { force = false; }
  16149. var wasPreviouslyBound = false;
  16150. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16151. this._activeChannel = texture._designatedSlot;
  16152. }
  16153. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16154. var isTextureForRendering = texture && texture._initialSlot > -1;
  16155. if (currentTextureBound !== texture || force) {
  16156. if (currentTextureBound) {
  16157. this._removeDesignatedSlot(currentTextureBound);
  16158. }
  16159. this._activateCurrentTexture();
  16160. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16161. this._boundTexturesCache[this._activeChannel] = texture;
  16162. if (texture) {
  16163. if (!this.disableTextureBindingOptimization) {
  16164. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16165. if (slotIndex > -1) {
  16166. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16167. }
  16168. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16169. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16170. }
  16171. texture._designatedSlot = this._activeChannel;
  16172. }
  16173. }
  16174. else if (forTextureDataUpdate) {
  16175. wasPreviouslyBound = true;
  16176. this._activateCurrentTexture();
  16177. }
  16178. if (isTextureForRendering && !forTextureDataUpdate) {
  16179. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16180. }
  16181. return wasPreviouslyBound;
  16182. };
  16183. /** @hidden */
  16184. Engine.prototype._bindTexture = function (channel, texture) {
  16185. if (channel < 0) {
  16186. return;
  16187. }
  16188. if (texture) {
  16189. channel = this._getCorrectTextureChannel(channel, texture);
  16190. }
  16191. this._activeChannel = channel;
  16192. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16193. };
  16194. /**
  16195. * Sets a texture to the webGL context from a postprocess
  16196. * @param channel defines the channel to use
  16197. * @param postProcess defines the source postprocess
  16198. */
  16199. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16200. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16201. };
  16202. /**
  16203. * Binds the output of the passed in post process to the texture channel specified
  16204. * @param channel The channel the texture should be bound to
  16205. * @param postProcess The post process which's output should be bound
  16206. */
  16207. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16208. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16209. };
  16210. /**
  16211. * Unbind all textures from the webGL context
  16212. */
  16213. Engine.prototype.unbindAllTextures = function () {
  16214. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16215. this._activeChannel = channel;
  16216. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16217. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16218. if (this.webGLVersion > 1) {
  16219. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16220. }
  16221. }
  16222. };
  16223. /**
  16224. * Sets a texture to the according uniform.
  16225. * @param channel The texture channel
  16226. * @param uniform The uniform to set
  16227. * @param texture The texture to apply
  16228. */
  16229. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16230. if (channel < 0) {
  16231. return;
  16232. }
  16233. if (uniform) {
  16234. this._boundUniforms[channel] = uniform;
  16235. }
  16236. this._setTexture(channel, texture);
  16237. };
  16238. /**
  16239. * Sets a depth stencil texture from a render target to the according uniform.
  16240. * @param channel The texture channel
  16241. * @param uniform The uniform to set
  16242. * @param texture The render target texture containing the depth stencil texture to apply
  16243. */
  16244. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16245. if (channel < 0) {
  16246. return;
  16247. }
  16248. if (uniform) {
  16249. this._boundUniforms[channel] = uniform;
  16250. }
  16251. if (!texture || !texture.depthStencilTexture) {
  16252. this._setTexture(channel, null);
  16253. }
  16254. else {
  16255. this._setTexture(channel, texture, false, true);
  16256. }
  16257. };
  16258. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16259. var uniform = this._boundUniforms[sourceSlot];
  16260. if (uniform._currentState === destination) {
  16261. return;
  16262. }
  16263. this._gl.uniform1i(uniform, destination);
  16264. uniform._currentState = destination;
  16265. };
  16266. Engine.prototype._getTextureWrapMode = function (mode) {
  16267. switch (mode) {
  16268. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16269. return this._gl.REPEAT;
  16270. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16271. return this._gl.CLAMP_TO_EDGE;
  16272. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16273. return this._gl.MIRRORED_REPEAT;
  16274. }
  16275. return this._gl.REPEAT;
  16276. };
  16277. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16278. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16279. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16280. // Not ready?
  16281. if (!texture) {
  16282. if (this._boundTexturesCache[channel] != null) {
  16283. this._activeChannel = channel;
  16284. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16285. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16286. if (this.webGLVersion > 1) {
  16287. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16288. }
  16289. }
  16290. return false;
  16291. }
  16292. // Video
  16293. if (texture.video) {
  16294. this._activeChannel = channel;
  16295. texture.update();
  16296. }
  16297. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16298. texture.delayLoad();
  16299. return false;
  16300. }
  16301. var internalTexture;
  16302. if (depthStencilTexture) {
  16303. internalTexture = texture.depthStencilTexture;
  16304. }
  16305. else if (texture.isReady()) {
  16306. internalTexture = texture.getInternalTexture();
  16307. }
  16308. else if (texture.isCube) {
  16309. internalTexture = this.emptyCubeTexture;
  16310. }
  16311. else if (texture.is3D) {
  16312. internalTexture = this.emptyTexture3D;
  16313. }
  16314. else {
  16315. internalTexture = this.emptyTexture;
  16316. }
  16317. if (!isPartOfTextureArray) {
  16318. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16319. }
  16320. var needToBind = true;
  16321. if (this._boundTexturesCache[channel] === internalTexture) {
  16322. this._moveBoundTextureOnTop(internalTexture);
  16323. if (!isPartOfTextureArray) {
  16324. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16325. }
  16326. needToBind = false;
  16327. }
  16328. this._activeChannel = channel;
  16329. if (internalTexture && internalTexture.is3D) {
  16330. if (needToBind) {
  16331. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16332. }
  16333. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16334. internalTexture._cachedWrapU = texture.wrapU;
  16335. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16336. }
  16337. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16338. internalTexture._cachedWrapV = texture.wrapV;
  16339. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16340. }
  16341. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16342. internalTexture._cachedWrapR = texture.wrapR;
  16343. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16344. }
  16345. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16346. }
  16347. else if (internalTexture && internalTexture.isCube) {
  16348. if (needToBind) {
  16349. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16350. }
  16351. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16352. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16353. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16354. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16355. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16356. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16357. }
  16358. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16359. }
  16360. else {
  16361. if (needToBind) {
  16362. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16363. }
  16364. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16365. internalTexture._cachedWrapU = texture.wrapU;
  16366. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16367. }
  16368. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16369. internalTexture._cachedWrapV = texture.wrapV;
  16370. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16371. }
  16372. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16373. }
  16374. return true;
  16375. };
  16376. /**
  16377. * Sets an array of texture to the webGL context
  16378. * @param channel defines the channel where the texture array must be set
  16379. * @param uniform defines the associated uniform location
  16380. * @param textures defines the array of textures to bind
  16381. */
  16382. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16383. if (channel < 0 || !uniform) {
  16384. return;
  16385. }
  16386. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16387. this._textureUnits = new Int32Array(textures.length);
  16388. }
  16389. for (var i = 0; i < textures.length; i++) {
  16390. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16391. }
  16392. this._gl.uniform1iv(uniform, this._textureUnits);
  16393. for (var index = 0; index < textures.length; index++) {
  16394. this._setTexture(this._textureUnits[index], textures[index], true);
  16395. }
  16396. };
  16397. /** @hidden */
  16398. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16399. var internalTexture = texture.getInternalTexture();
  16400. if (!internalTexture) {
  16401. return;
  16402. }
  16403. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16404. var value = texture.anisotropicFilteringLevel;
  16405. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16406. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16407. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16408. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16409. }
  16410. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16411. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16412. internalTexture._cachedAnisotropicFilteringLevel = value;
  16413. }
  16414. };
  16415. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16416. this._bindTextureDirectly(target, texture, true, true);
  16417. this._gl.texParameterf(target, parameter, value);
  16418. };
  16419. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16420. if (texture) {
  16421. this._bindTextureDirectly(target, texture, true, true);
  16422. }
  16423. this._gl.texParameteri(target, parameter, value);
  16424. };
  16425. /**
  16426. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16427. * @param x defines the x coordinate of the rectangle where pixels must be read
  16428. * @param y defines the y coordinate of the rectangle where pixels must be read
  16429. * @param width defines the width of the rectangle where pixels must be read
  16430. * @param height defines the height of the rectangle where pixels must be read
  16431. * @returns a Uint8Array containing RGBA colors
  16432. */
  16433. Engine.prototype.readPixels = function (x, y, width, height) {
  16434. var data = new Uint8Array(height * width * 4);
  16435. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16436. return data;
  16437. };
  16438. /**
  16439. * Add an externaly attached data from its key.
  16440. * This method call will fail and return false, if such key already exists.
  16441. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16442. * @param key the unique key that identifies the data
  16443. * @param data the data object to associate to the key for this Engine instance
  16444. * @return true if no such key were already present and the data was added successfully, false otherwise
  16445. */
  16446. Engine.prototype.addExternalData = function (key, data) {
  16447. if (!this._externalData) {
  16448. this._externalData = new BABYLON.StringDictionary();
  16449. }
  16450. return this._externalData.add(key, data);
  16451. };
  16452. /**
  16453. * Get an externaly attached data from its key
  16454. * @param key the unique key that identifies the data
  16455. * @return the associated data, if present (can be null), or undefined if not present
  16456. */
  16457. Engine.prototype.getExternalData = function (key) {
  16458. if (!this._externalData) {
  16459. this._externalData = new BABYLON.StringDictionary();
  16460. }
  16461. return this._externalData.get(key);
  16462. };
  16463. /**
  16464. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16465. * @param key the unique key that identifies the data
  16466. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16467. * @return the associated data, can be null if the factory returned null.
  16468. */
  16469. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16470. if (!this._externalData) {
  16471. this._externalData = new BABYLON.StringDictionary();
  16472. }
  16473. return this._externalData.getOrAddWithFactory(key, factory);
  16474. };
  16475. /**
  16476. * Remove an externaly attached data from the Engine instance
  16477. * @param key the unique key that identifies the data
  16478. * @return true if the data was successfully removed, false if it doesn't exist
  16479. */
  16480. Engine.prototype.removeExternalData = function (key) {
  16481. if (!this._externalData) {
  16482. this._externalData = new BABYLON.StringDictionary();
  16483. }
  16484. return this._externalData.remove(key);
  16485. };
  16486. /**
  16487. * Unbind all vertex attributes from the webGL context
  16488. */
  16489. Engine.prototype.unbindAllAttributes = function () {
  16490. if (this._mustWipeVertexAttributes) {
  16491. this._mustWipeVertexAttributes = false;
  16492. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16493. this._gl.disableVertexAttribArray(i);
  16494. this._vertexAttribArraysEnabled[i] = false;
  16495. this._currentBufferPointers[i].active = false;
  16496. }
  16497. return;
  16498. }
  16499. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16500. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16501. continue;
  16502. }
  16503. this._gl.disableVertexAttribArray(i);
  16504. this._vertexAttribArraysEnabled[i] = false;
  16505. this._currentBufferPointers[i].active = false;
  16506. }
  16507. };
  16508. /**
  16509. * 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
  16510. */
  16511. Engine.prototype.releaseEffects = function () {
  16512. for (var name in this._compiledEffects) {
  16513. this._deleteProgram(this._compiledEffects[name]._program);
  16514. }
  16515. this._compiledEffects = {};
  16516. };
  16517. /**
  16518. * Dispose and release all associated resources
  16519. */
  16520. Engine.prototype.dispose = function () {
  16521. this.hideLoadingUI();
  16522. this.stopRenderLoop();
  16523. // Release postProcesses
  16524. while (this.postProcesses.length) {
  16525. this.postProcesses[0].dispose();
  16526. }
  16527. // Empty texture
  16528. if (this._emptyTexture) {
  16529. this._releaseTexture(this._emptyTexture);
  16530. this._emptyTexture = null;
  16531. }
  16532. if (this._emptyCubeTexture) {
  16533. this._releaseTexture(this._emptyCubeTexture);
  16534. this._emptyCubeTexture = null;
  16535. }
  16536. // Rescale PP
  16537. if (this._rescalePostProcess) {
  16538. this._rescalePostProcess.dispose();
  16539. }
  16540. // Release scenes
  16541. while (this.scenes.length) {
  16542. this.scenes[0].dispose();
  16543. }
  16544. // Release audio engine
  16545. if (Engine.audioEngine) {
  16546. Engine.audioEngine.dispose();
  16547. }
  16548. // Release effects
  16549. this.releaseEffects();
  16550. // Unbind
  16551. this.unbindAllAttributes();
  16552. this._boundUniforms = [];
  16553. if (this._dummyFramebuffer) {
  16554. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16555. }
  16556. //WebVR
  16557. this.disableVR();
  16558. // Events
  16559. if (BABYLON.Tools.IsWindowObjectExist()) {
  16560. window.removeEventListener("blur", this._onBlur);
  16561. window.removeEventListener("focus", this._onFocus);
  16562. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16563. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16564. if (this._renderingCanvas) {
  16565. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16566. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16567. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16568. if (!this._doNotHandleContextLost) {
  16569. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16570. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16571. }
  16572. }
  16573. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16574. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16575. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16576. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16577. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16578. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16579. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16580. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16581. if (this._onVrDisplayConnect) {
  16582. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16583. if (this._onVrDisplayDisconnect) {
  16584. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16585. }
  16586. if (this._onVrDisplayPresentChange) {
  16587. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16588. }
  16589. this._onVrDisplayConnect = null;
  16590. this._onVrDisplayDisconnect = null;
  16591. }
  16592. }
  16593. // Remove from Instances
  16594. var index = Engine.Instances.indexOf(this);
  16595. if (index >= 0) {
  16596. Engine.Instances.splice(index, 1);
  16597. }
  16598. this._workingCanvas = null;
  16599. this._workingContext = null;
  16600. this._currentBufferPointers = [];
  16601. this._renderingCanvas = null;
  16602. this._currentProgram = null;
  16603. this._bindedRenderFunction = null;
  16604. this.onResizeObservable.clear();
  16605. this.onCanvasBlurObservable.clear();
  16606. this.onCanvasFocusObservable.clear();
  16607. this.onCanvasPointerOutObservable.clear();
  16608. this.onBeginFrameObservable.clear();
  16609. this.onEndFrameObservable.clear();
  16610. BABYLON.Effect.ResetCache();
  16611. // Abort active requests
  16612. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16613. var request = _a[_i];
  16614. request.abort();
  16615. }
  16616. };
  16617. // Loading screen
  16618. /**
  16619. * Display the loading screen
  16620. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16621. */
  16622. Engine.prototype.displayLoadingUI = function () {
  16623. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16624. return;
  16625. }
  16626. var loadingScreen = this.loadingScreen;
  16627. if (loadingScreen) {
  16628. loadingScreen.displayLoadingUI();
  16629. }
  16630. };
  16631. /**
  16632. * Hide the loading screen
  16633. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16634. */
  16635. Engine.prototype.hideLoadingUI = function () {
  16636. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16637. return;
  16638. }
  16639. var loadingScreen = this.loadingScreen;
  16640. if (loadingScreen) {
  16641. loadingScreen.hideLoadingUI();
  16642. }
  16643. };
  16644. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16645. /**
  16646. * Gets the current loading screen object
  16647. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16648. */
  16649. get: function () {
  16650. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16651. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16652. return this._loadingScreen;
  16653. },
  16654. /**
  16655. * Sets the current loading screen object
  16656. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16657. */
  16658. set: function (loadingScreen) {
  16659. this._loadingScreen = loadingScreen;
  16660. },
  16661. enumerable: true,
  16662. configurable: true
  16663. });
  16664. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16665. /**
  16666. * Sets the current loading screen text
  16667. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16668. */
  16669. set: function (text) {
  16670. this.loadingScreen.loadingUIText = text;
  16671. },
  16672. enumerable: true,
  16673. configurable: true
  16674. });
  16675. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16676. /**
  16677. * Sets the current loading screen background color
  16678. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16679. */
  16680. set: function (color) {
  16681. this.loadingScreen.loadingUIBackgroundColor = color;
  16682. },
  16683. enumerable: true,
  16684. configurable: true
  16685. });
  16686. /**
  16687. * Attach a new callback raised when context lost event is fired
  16688. * @param callback defines the callback to call
  16689. */
  16690. Engine.prototype.attachContextLostEvent = function (callback) {
  16691. if (this._renderingCanvas) {
  16692. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16693. }
  16694. };
  16695. /**
  16696. * Attach a new callback raised when context restored event is fired
  16697. * @param callback defines the callback to call
  16698. */
  16699. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16700. if (this._renderingCanvas) {
  16701. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16702. }
  16703. };
  16704. /**
  16705. * Gets the source code of the vertex shader associated with a specific webGL program
  16706. * @param program defines the program to use
  16707. * @returns a string containing the source code of the vertex shader associated with the program
  16708. */
  16709. Engine.prototype.getVertexShaderSource = function (program) {
  16710. var shaders = this._gl.getAttachedShaders(program);
  16711. if (!shaders) {
  16712. return null;
  16713. }
  16714. return this._gl.getShaderSource(shaders[0]);
  16715. };
  16716. /**
  16717. * Gets the source code of the fragment shader associated with a specific webGL program
  16718. * @param program defines the program to use
  16719. * @returns a string containing the source code of the fragment shader associated with the program
  16720. */
  16721. Engine.prototype.getFragmentShaderSource = function (program) {
  16722. var shaders = this._gl.getAttachedShaders(program);
  16723. if (!shaders) {
  16724. return null;
  16725. }
  16726. return this._gl.getShaderSource(shaders[1]);
  16727. };
  16728. /**
  16729. * Get the current error code of the webGL context
  16730. * @returns the error code
  16731. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16732. */
  16733. Engine.prototype.getError = function () {
  16734. return this._gl.getError();
  16735. };
  16736. // FPS
  16737. /**
  16738. * Gets the current framerate
  16739. * @returns a number representing the framerate
  16740. */
  16741. Engine.prototype.getFps = function () {
  16742. return this._fps;
  16743. };
  16744. /**
  16745. * Gets the time spent between current and previous frame
  16746. * @returns a number representing the delta time in ms
  16747. */
  16748. Engine.prototype.getDeltaTime = function () {
  16749. return this._deltaTime;
  16750. };
  16751. Engine.prototype._measureFps = function () {
  16752. this._performanceMonitor.sampleFrame();
  16753. this._fps = this._performanceMonitor.averageFPS;
  16754. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16755. };
  16756. /** @hidden */
  16757. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16758. if (faceIndex === void 0) { faceIndex = -1; }
  16759. if (level === void 0) { level = 0; }
  16760. var gl = this._gl;
  16761. if (!this._dummyFramebuffer) {
  16762. var dummy = gl.createFramebuffer();
  16763. if (!dummy) {
  16764. throw new Error("Unable to create dummy framebuffer");
  16765. }
  16766. this._dummyFramebuffer = dummy;
  16767. }
  16768. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16769. if (faceIndex > -1) {
  16770. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16771. }
  16772. else {
  16773. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16774. }
  16775. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16776. var buffer;
  16777. switch (readType) {
  16778. case gl.UNSIGNED_BYTE:
  16779. buffer = new Uint8Array(4 * width * height);
  16780. readType = gl.UNSIGNED_BYTE;
  16781. break;
  16782. default:
  16783. buffer = new Float32Array(4 * width * height);
  16784. readType = gl.FLOAT;
  16785. break;
  16786. }
  16787. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16788. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16789. return buffer;
  16790. };
  16791. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16792. if (this._webGLVersion > 1) {
  16793. return this._caps.colorBufferFloat;
  16794. }
  16795. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16796. };
  16797. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16798. if (this._webGLVersion > 1) {
  16799. return this._caps.colorBufferFloat;
  16800. }
  16801. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16802. };
  16803. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16804. Engine.prototype._canRenderToFramebuffer = function (type) {
  16805. var gl = this._gl;
  16806. //clear existing errors
  16807. while (gl.getError() !== gl.NO_ERROR) { }
  16808. var successful = true;
  16809. var texture = gl.createTexture();
  16810. gl.bindTexture(gl.TEXTURE_2D, texture);
  16811. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16814. var fb = gl.createFramebuffer();
  16815. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16816. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16817. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16818. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16819. successful = successful && (gl.getError() === gl.NO_ERROR);
  16820. //try render by clearing frame buffer's color buffer
  16821. if (successful) {
  16822. gl.clear(gl.COLOR_BUFFER_BIT);
  16823. successful = successful && (gl.getError() === gl.NO_ERROR);
  16824. }
  16825. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16826. if (successful) {
  16827. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16828. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16829. var readFormat = gl.RGBA;
  16830. var readType = gl.UNSIGNED_BYTE;
  16831. var buffer = new Uint8Array(4);
  16832. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16833. successful = successful && (gl.getError() === gl.NO_ERROR);
  16834. }
  16835. //clean up
  16836. gl.deleteTexture(texture);
  16837. gl.deleteFramebuffer(fb);
  16838. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16839. //clear accumulated errors
  16840. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16841. return successful;
  16842. };
  16843. /** @hidden */
  16844. Engine.prototype._getWebGLTextureType = function (type) {
  16845. if (type === Engine.TEXTURETYPE_FLOAT) {
  16846. return this._gl.FLOAT;
  16847. }
  16848. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16849. // Add Half Float Constant.
  16850. return this._gl.HALF_FLOAT_OES;
  16851. }
  16852. return this._gl.UNSIGNED_BYTE;
  16853. };
  16854. ;
  16855. Engine.prototype._getInternalFormat = function (format) {
  16856. var internalFormat = this._gl.RGBA;
  16857. switch (format) {
  16858. case Engine.TEXTUREFORMAT_ALPHA:
  16859. internalFormat = this._gl.ALPHA;
  16860. break;
  16861. case Engine.TEXTUREFORMAT_LUMINANCE:
  16862. internalFormat = this._gl.LUMINANCE;
  16863. break;
  16864. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16865. internalFormat = this._gl.LUMINANCE_ALPHA;
  16866. break;
  16867. case Engine.TEXTUREFORMAT_RGB:
  16868. internalFormat = this._gl.RGB;
  16869. break;
  16870. case Engine.TEXTUREFORMAT_RGBA:
  16871. internalFormat = this._gl.RGBA;
  16872. break;
  16873. case Engine.TEXTUREFORMAT_R:
  16874. internalFormat = this._gl.RED;
  16875. break;
  16876. case Engine.TEXTUREFORMAT_RG:
  16877. internalFormat = this._gl.RG;
  16878. break;
  16879. }
  16880. return internalFormat;
  16881. };
  16882. /** @hidden */
  16883. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16884. if (this._webGLVersion === 1) {
  16885. if (format !== undefined) {
  16886. switch (format) {
  16887. case Engine.TEXTUREFORMAT_LUMINANCE:
  16888. return this._gl.LUMINANCE;
  16889. case Engine.TEXTUREFORMAT_ALPHA:
  16890. return this._gl.ALPHA;
  16891. }
  16892. }
  16893. return this._gl.RGBA;
  16894. }
  16895. if (type === Engine.TEXTURETYPE_FLOAT) {
  16896. if (format !== undefined) {
  16897. switch (format) {
  16898. case Engine.TEXTUREFORMAT_R:
  16899. return this._gl.R32F;
  16900. case Engine.TEXTUREFORMAT_RG:
  16901. return this._gl.RG32F;
  16902. case Engine.TEXTUREFORMAT_RGB:
  16903. return this._gl.RGB32F;
  16904. }
  16905. }
  16906. return this._gl.RGBA32F;
  16907. }
  16908. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16909. if (format) {
  16910. switch (format) {
  16911. case Engine.TEXTUREFORMAT_R:
  16912. return this._gl.R16F;
  16913. case Engine.TEXTUREFORMAT_RG:
  16914. return this._gl.RG16F;
  16915. case Engine.TEXTUREFORMAT_RGB:
  16916. return this._gl.RGB16F;
  16917. }
  16918. }
  16919. return this._gl.RGBA16F;
  16920. }
  16921. if (format !== undefined) {
  16922. switch (format) {
  16923. case Engine.TEXTUREFORMAT_LUMINANCE:
  16924. return this._gl.LUMINANCE;
  16925. case Engine.TEXTUREFORMAT_RGB:
  16926. return this._gl.RGB;
  16927. case Engine.TEXTUREFORMAT_R:
  16928. return this._gl.R8;
  16929. case Engine.TEXTUREFORMAT_RG:
  16930. return this._gl.RG8;
  16931. case Engine.TEXTUREFORMAT_ALPHA:
  16932. return this._gl.ALPHA;
  16933. }
  16934. }
  16935. return this._gl.RGBA;
  16936. };
  16937. ;
  16938. /** @hidden */
  16939. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16940. if (type === Engine.TEXTURETYPE_FLOAT) {
  16941. return this._gl.RGBA32F;
  16942. }
  16943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16944. return this._gl.RGBA16F;
  16945. }
  16946. return this._gl.RGBA8;
  16947. };
  16948. ;
  16949. /** @hidden */
  16950. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  16951. var _this = this;
  16952. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  16953. this._activeRequests.push(request);
  16954. request.onCompleteObservable.add(function (request) {
  16955. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  16956. });
  16957. return request;
  16958. };
  16959. /** @hidden */
  16960. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  16961. var _this = this;
  16962. return new Promise(function (resolve, reject) {
  16963. _this._loadFile(url, function (data) {
  16964. resolve(data);
  16965. }, undefined, database, useArrayBuffer, function (request, exception) {
  16966. reject(exception);
  16967. });
  16968. });
  16969. };
  16970. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  16971. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  16972. var onload = function (data) {
  16973. loadedFiles[index] = data;
  16974. loadedFiles._internalCount++;
  16975. if (loadedFiles._internalCount === 6) {
  16976. onfinish(loadedFiles);
  16977. }
  16978. };
  16979. var onerror = function (request, exception) {
  16980. if (onErrorCallBack && request) {
  16981. onErrorCallBack(request.status + " " + request.statusText, exception);
  16982. }
  16983. };
  16984. this._loadFile(url, onload, undefined, undefined, true, onerror);
  16985. };
  16986. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  16987. if (onError === void 0) { onError = null; }
  16988. var loadedFiles = [];
  16989. loadedFiles._internalCount = 0;
  16990. for (var index = 0; index < 6; index++) {
  16991. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  16992. }
  16993. };
  16994. // Statics
  16995. /**
  16996. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  16997. * @returns true if the engine can be created
  16998. * @ignorenaming
  16999. */
  17000. Engine.isSupported = function () {
  17001. try {
  17002. var tempcanvas = document.createElement("canvas");
  17003. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17004. return gl != null && !!window.WebGLRenderingContext;
  17005. }
  17006. catch (e) {
  17007. return false;
  17008. }
  17009. };
  17010. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17011. Engine.ExceptionList = [
  17012. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17013. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17014. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17015. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17016. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17017. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17018. ];
  17019. /** Gets the list of created engines */
  17020. Engine.Instances = new Array();
  17021. /**
  17022. * Hidden
  17023. */
  17024. Engine._TextureLoaders = [];
  17025. // Const statics
  17026. /** Defines that alpha blending is disabled */
  17027. Engine.ALPHA_DISABLE = 0;
  17028. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17029. Engine.ALPHA_ADD = 1;
  17030. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17031. Engine.ALPHA_COMBINE = 2;
  17032. /** Defines that alpha blending to DEST - SRC * DEST */
  17033. Engine.ALPHA_SUBTRACT = 3;
  17034. /** Defines that alpha blending to SRC * DEST */
  17035. Engine.ALPHA_MULTIPLY = 4;
  17036. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17037. Engine.ALPHA_MAXIMIZED = 5;
  17038. /** Defines that alpha blending to SRC + DEST */
  17039. Engine.ALPHA_ONEONE = 6;
  17040. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17041. Engine.ALPHA_PREMULTIPLIED = 7;
  17042. /**
  17043. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17044. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17045. */
  17046. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17047. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17048. Engine.ALPHA_INTERPOLATE = 9;
  17049. /**
  17050. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17051. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17052. */
  17053. Engine.ALPHA_SCREENMODE = 10;
  17054. /** Defines that the ressource is not delayed*/
  17055. Engine.DELAYLOADSTATE_NONE = 0;
  17056. /** Defines that the ressource was successfully delay loaded */
  17057. Engine.DELAYLOADSTATE_LOADED = 1;
  17058. /** Defines that the ressource is currently delay loading */
  17059. Engine.DELAYLOADSTATE_LOADING = 2;
  17060. /** Defines that the ressource is delayed and has not started loading */
  17061. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17062. // Depht or Stencil test Constants.
  17063. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17064. Engine.NEVER = 0x0200;
  17065. /** 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 */
  17066. Engine.ALWAYS = 0x0207;
  17067. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17068. Engine.LESS = 0x0201;
  17069. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17070. Engine.EQUAL = 0x0202;
  17071. /** 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 */
  17072. Engine.LEQUAL = 0x0203;
  17073. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17074. Engine.GREATER = 0x0204;
  17075. /** 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 */
  17076. Engine.GEQUAL = 0x0206;
  17077. /** 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 */
  17078. Engine.NOTEQUAL = 0x0205;
  17079. // Stencil Actions Constants.
  17080. /** Passed to stencilOperation to specify that stencil value must be kept */
  17081. Engine.KEEP = 0x1E00;
  17082. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17083. Engine.REPLACE = 0x1E01;
  17084. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17085. Engine.INCR = 0x1E02;
  17086. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17087. Engine.DECR = 0x1E03;
  17088. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17089. Engine.INVERT = 0x150A;
  17090. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17091. Engine.INCR_WRAP = 0x8507;
  17092. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17093. Engine.DECR_WRAP = 0x8508;
  17094. /** Texture is not repeating outside of 0..1 UVs */
  17095. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17096. /** Texture is repeating outside of 0..1 UVs */
  17097. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17098. /** Texture is repeating and mirrored */
  17099. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17100. /** ALPHA */
  17101. Engine.TEXTUREFORMAT_ALPHA = 0;
  17102. /** LUMINANCE */
  17103. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17104. /** LUMINANCE_ALPHA */
  17105. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17106. /** RGB */
  17107. Engine.TEXTUREFORMAT_RGB = 4;
  17108. /** RGBA */
  17109. Engine.TEXTUREFORMAT_RGBA = 5;
  17110. /** R */
  17111. Engine.TEXTUREFORMAT_R = 6;
  17112. /** RG */
  17113. Engine.TEXTUREFORMAT_RG = 7;
  17114. /** UNSIGNED_INT */
  17115. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17116. /** FLOAT */
  17117. Engine.TEXTURETYPE_FLOAT = 1;
  17118. /** HALF_FLOAT */
  17119. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17120. /** nearest is mag = nearest and min = nearest and mip = linear */
  17121. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17122. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17123. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17124. /** Trilinear is mag = linear and min = linear and mip = linear */
  17125. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17126. /** nearest is mag = nearest and min = nearest and mip = linear */
  17127. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17128. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17129. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17130. /** Trilinear is mag = linear and min = linear and mip = linear */
  17131. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17132. /** mag = nearest and min = nearest and mip = nearest */
  17133. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17134. /** mag = nearest and min = linear and mip = nearest */
  17135. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17136. /** mag = nearest and min = linear and mip = linear */
  17137. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17138. /** mag = nearest and min = linear and mip = none */
  17139. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17140. /** mag = nearest and min = nearest and mip = none */
  17141. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17142. /** mag = linear and min = nearest and mip = nearest */
  17143. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17144. /** mag = linear and min = nearest and mip = linear */
  17145. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17146. /** mag = linear and min = linear and mip = none */
  17147. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17148. /** mag = linear and min = nearest and mip = none */
  17149. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17150. /** Explicit coordinates mode */
  17151. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17152. /** Spherical coordinates mode */
  17153. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17154. /** Planar coordinates mode */
  17155. Engine.TEXTURE_PLANAR_MODE = 2;
  17156. /** Cubic coordinates mode */
  17157. Engine.TEXTURE_CUBIC_MODE = 3;
  17158. /** Projection coordinates mode */
  17159. Engine.TEXTURE_PROJECTION_MODE = 4;
  17160. /** Skybox coordinates mode */
  17161. Engine.TEXTURE_SKYBOX_MODE = 5;
  17162. /** Inverse Cubic coordinates mode */
  17163. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17164. /** Equirectangular coordinates mode */
  17165. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17166. /** Equirectangular Fixed coordinates mode */
  17167. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17168. /** Equirectangular Fixed Mirrored coordinates mode */
  17169. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17170. // Texture rescaling mode
  17171. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17172. Engine.SCALEMODE_FLOOR = 1;
  17173. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17174. Engine.SCALEMODE_NEAREST = 2;
  17175. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17176. Engine.SCALEMODE_CEILING = 3;
  17177. // Updatable statics so stick with vars here
  17178. /**
  17179. * Gets or sets the epsilon value used by collision engine
  17180. */
  17181. Engine.CollisionsEpsilon = 0.001;
  17182. /**
  17183. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17184. */
  17185. Engine.CodeRepository = "src/";
  17186. /**
  17187. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17188. */
  17189. Engine.ShadersRepository = "src/Shaders/";
  17190. return Engine;
  17191. }());
  17192. BABYLON.Engine = Engine;
  17193. })(BABYLON || (BABYLON = {}));
  17194. //# sourceMappingURL=babylon.engine.js.map
  17195. var BABYLON;
  17196. (function (BABYLON) {
  17197. /**
  17198. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17199. */
  17200. var Node = /** @class */ (function () {
  17201. /**
  17202. * Creates a new Node
  17203. * @param {string} name - the name and id to be given to this node
  17204. * @param {BABYLON.Scene} the scene this node will be added to
  17205. */
  17206. function Node(name, scene) {
  17207. if (scene === void 0) { scene = null; }
  17208. /**
  17209. * Gets or sets a string used to store user defined state for the node
  17210. */
  17211. this.state = "";
  17212. /**
  17213. * Gets or sets an object used to store user defined information for the node
  17214. */
  17215. this.metadata = null;
  17216. /**
  17217. * Gets or sets a boolean used to define if the node must be serialized
  17218. */
  17219. this.doNotSerialize = false;
  17220. /** @hidden */
  17221. this._isDisposed = false;
  17222. /**
  17223. * Gets a list of Animations associated with the node
  17224. */
  17225. this.animations = new Array();
  17226. this._ranges = {};
  17227. this._isEnabled = true;
  17228. this._isReady = true;
  17229. /** @hidden */
  17230. this._currentRenderId = -1;
  17231. this._parentRenderId = -1;
  17232. this._childRenderId = -1;
  17233. this._animationPropertiesOverride = null;
  17234. /**
  17235. * An event triggered when the mesh is disposed
  17236. */
  17237. this.onDisposeObservable = new BABYLON.Observable();
  17238. // Behaviors
  17239. this._behaviors = new Array();
  17240. this.name = name;
  17241. this.id = name;
  17242. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17243. this.uniqueId = this._scene.getUniqueId();
  17244. this._initCache();
  17245. }
  17246. /**
  17247. * Add a new node constructor
  17248. * @param type defines the type name of the node to construct
  17249. * @param constructorFunc defines the constructor function
  17250. */
  17251. Node.AddNodeConstructor = function (type, constructorFunc) {
  17252. this._NodeConstructors[type] = constructorFunc;
  17253. };
  17254. /**
  17255. * Returns a node constructor based on type name
  17256. * @param type defines the type name
  17257. * @param name defines the new node name
  17258. * @param scene defines the hosting scene
  17259. * @param options defines optional options to transmit to constructors
  17260. * @returns the new constructor or null
  17261. */
  17262. Node.Construct = function (type, name, scene, options) {
  17263. var constructorFunc = this._NodeConstructors[type];
  17264. if (!constructorFunc) {
  17265. return null;
  17266. }
  17267. return constructorFunc(name, scene, options);
  17268. };
  17269. /**
  17270. * Gets a boolean indicating if the node has been disposed
  17271. * @returns true if the node was disposed
  17272. */
  17273. Node.prototype.isDisposed = function () {
  17274. return this._isDisposed;
  17275. };
  17276. Object.defineProperty(Node.prototype, "parent", {
  17277. get: function () {
  17278. return this._parentNode;
  17279. },
  17280. /**
  17281. * Gets or sets the parent of the node
  17282. */
  17283. set: function (parent) {
  17284. if (this._parentNode === parent) {
  17285. return;
  17286. }
  17287. // Remove self from list of children of parent
  17288. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17289. var index = this._parentNode._children.indexOf(this);
  17290. if (index !== -1) {
  17291. this._parentNode._children.splice(index, 1);
  17292. }
  17293. }
  17294. // Store new parent
  17295. this._parentNode = parent;
  17296. // Add as child to new parent
  17297. if (this._parentNode) {
  17298. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17299. this._parentNode._children = new Array();
  17300. }
  17301. this._parentNode._children.push(this);
  17302. }
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17308. /**
  17309. * Gets or sets the animation properties override
  17310. */
  17311. get: function () {
  17312. if (!this._animationPropertiesOverride) {
  17313. return this._scene.animationPropertiesOverride;
  17314. }
  17315. return this._animationPropertiesOverride;
  17316. },
  17317. set: function (value) {
  17318. this._animationPropertiesOverride = value;
  17319. },
  17320. enumerable: true,
  17321. configurable: true
  17322. });
  17323. /**
  17324. * Gets a string idenfifying the name of the class
  17325. * @returns "Node" string
  17326. */
  17327. Node.prototype.getClassName = function () {
  17328. return "Node";
  17329. };
  17330. Object.defineProperty(Node.prototype, "onDispose", {
  17331. /**
  17332. * Sets a callback that will be raised when the node will be disposed
  17333. */
  17334. set: function (callback) {
  17335. if (this._onDisposeObserver) {
  17336. this.onDisposeObservable.remove(this._onDisposeObserver);
  17337. }
  17338. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. /**
  17344. * Gets the scene of the node
  17345. * @returns a {BABYLON.Scene}
  17346. */
  17347. Node.prototype.getScene = function () {
  17348. return this._scene;
  17349. };
  17350. /**
  17351. * Gets the engine of the node
  17352. * @returns a {BABYLON.Engine}
  17353. */
  17354. Node.prototype.getEngine = function () {
  17355. return this._scene.getEngine();
  17356. };
  17357. /**
  17358. * Attach a behavior to the node
  17359. * @see http://doc.babylonjs.com/features/behaviour
  17360. * @param behavior defines the behavior to attach
  17361. * @returns the current Node
  17362. */
  17363. Node.prototype.addBehavior = function (behavior) {
  17364. var _this = this;
  17365. var index = this._behaviors.indexOf(behavior);
  17366. if (index !== -1) {
  17367. return this;
  17368. }
  17369. behavior.init();
  17370. if (this._scene.isLoading) {
  17371. // We defer the attach when the scene will be loaded
  17372. this._scene.onDataLoadedObservable.addOnce(function () {
  17373. behavior.attach(_this);
  17374. });
  17375. }
  17376. else {
  17377. behavior.attach(this);
  17378. }
  17379. this._behaviors.push(behavior);
  17380. return this;
  17381. };
  17382. /**
  17383. * Remove an attached behavior
  17384. * @see http://doc.babylonjs.com/features/behaviour
  17385. * @param behavior defines the behavior to attach
  17386. * @returns the current Node
  17387. */
  17388. Node.prototype.removeBehavior = function (behavior) {
  17389. var index = this._behaviors.indexOf(behavior);
  17390. if (index === -1) {
  17391. return this;
  17392. }
  17393. this._behaviors[index].detach();
  17394. this._behaviors.splice(index, 1);
  17395. return this;
  17396. };
  17397. Object.defineProperty(Node.prototype, "behaviors", {
  17398. /**
  17399. * Gets the list of attached behaviors
  17400. * @see http://doc.babylonjs.com/features/behaviour
  17401. */
  17402. get: function () {
  17403. return this._behaviors;
  17404. },
  17405. enumerable: true,
  17406. configurable: true
  17407. });
  17408. /**
  17409. * Gets an attached behavior by name
  17410. * @param name defines the name of the behavior to look for
  17411. * @see http://doc.babylonjs.com/features/behaviour
  17412. * @returns null if behavior was not found else the requested behavior
  17413. */
  17414. Node.prototype.getBehaviorByName = function (name) {
  17415. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17416. var behavior = _a[_i];
  17417. if (behavior.name === name) {
  17418. return behavior;
  17419. }
  17420. }
  17421. return null;
  17422. };
  17423. /**
  17424. * Returns the world matrix of the node
  17425. * @returns a matrix containing the node's world matrix
  17426. */
  17427. Node.prototype.getWorldMatrix = function () {
  17428. return BABYLON.Matrix.Identity();
  17429. };
  17430. /** @hidden */
  17431. Node.prototype._getWorldMatrixDeterminant = function () {
  17432. return 1;
  17433. };
  17434. // override it in derived class if you add new variables to the cache
  17435. // and call the parent class method
  17436. /** @hidden */
  17437. Node.prototype._initCache = function () {
  17438. this._cache = {};
  17439. this._cache.parent = undefined;
  17440. };
  17441. /** @hidden */
  17442. Node.prototype.updateCache = function (force) {
  17443. if (!force && this.isSynchronized())
  17444. return;
  17445. this._cache.parent = this.parent;
  17446. this._updateCache();
  17447. };
  17448. // override it in derived class if you add new variables to the cache
  17449. // and call the parent class method if !ignoreParentClass
  17450. /** @hidden */
  17451. Node.prototype._updateCache = function (ignoreParentClass) {
  17452. };
  17453. // override it in derived class if you add new variables to the cache
  17454. /** @hidden */
  17455. Node.prototype._isSynchronized = function () {
  17456. return true;
  17457. };
  17458. /** @hidden */
  17459. Node.prototype._markSyncedWithParent = function () {
  17460. if (this.parent) {
  17461. this._parentRenderId = this.parent._childRenderId;
  17462. }
  17463. };
  17464. /** @hidden */
  17465. Node.prototype.isSynchronizedWithParent = function () {
  17466. if (!this.parent) {
  17467. return true;
  17468. }
  17469. if (this._parentRenderId !== this.parent._childRenderId) {
  17470. return false;
  17471. }
  17472. return this.parent.isSynchronized();
  17473. };
  17474. /** @hidden */
  17475. Node.prototype.isSynchronized = function (updateCache) {
  17476. var check = this.hasNewParent();
  17477. check = check || !this.isSynchronizedWithParent();
  17478. check = check || !this._isSynchronized();
  17479. if (updateCache)
  17480. this.updateCache(true);
  17481. return !check;
  17482. };
  17483. /** @hidden */
  17484. Node.prototype.hasNewParent = function (update) {
  17485. if (this._cache.parent === this.parent)
  17486. return false;
  17487. if (update)
  17488. this._cache.parent = this.parent;
  17489. return true;
  17490. };
  17491. /**
  17492. * Is this node ready to be used/rendered
  17493. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17494. * @return true if the node is ready
  17495. */
  17496. Node.prototype.isReady = function (completeCheck) {
  17497. if (completeCheck === void 0) { completeCheck = false; }
  17498. return this._isReady;
  17499. };
  17500. /**
  17501. * Is this node enabled?
  17502. * 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
  17503. * @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
  17504. * @return whether this node (and its parent) is enabled
  17505. */
  17506. Node.prototype.isEnabled = function (checkAncestors) {
  17507. if (checkAncestors === void 0) { checkAncestors = true; }
  17508. if (checkAncestors === false) {
  17509. return this._isEnabled;
  17510. }
  17511. if (this._isEnabled === false) {
  17512. return false;
  17513. }
  17514. if (this.parent !== undefined && this.parent !== null) {
  17515. return this.parent.isEnabled(checkAncestors);
  17516. }
  17517. return true;
  17518. };
  17519. /**
  17520. * Set the enabled state of this node
  17521. * @param value defines the new enabled state
  17522. */
  17523. Node.prototype.setEnabled = function (value) {
  17524. this._isEnabled = value;
  17525. };
  17526. /**
  17527. * Is this node a descendant of the given node?
  17528. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17529. * @param ancestor defines the parent node to inspect
  17530. * @returns a boolean indicating if this node is a descendant of the given node
  17531. */
  17532. Node.prototype.isDescendantOf = function (ancestor) {
  17533. if (this.parent) {
  17534. if (this.parent === ancestor) {
  17535. return true;
  17536. }
  17537. return this.parent.isDescendantOf(ancestor);
  17538. }
  17539. return false;
  17540. };
  17541. /** @hidden */
  17542. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17543. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17544. if (!this._children) {
  17545. return;
  17546. }
  17547. for (var index = 0; index < this._children.length; index++) {
  17548. var item = this._children[index];
  17549. if (!predicate || predicate(item)) {
  17550. results.push(item);
  17551. }
  17552. if (!directDescendantsOnly) {
  17553. item._getDescendants(results, false, predicate);
  17554. }
  17555. }
  17556. };
  17557. /**
  17558. * Will return all nodes that have this node as ascendant
  17559. * @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
  17560. * @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
  17561. * @return all children nodes of all types
  17562. */
  17563. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17564. var results = new Array();
  17565. this._getDescendants(results, directDescendantsOnly, predicate);
  17566. return results;
  17567. };
  17568. /**
  17569. * Get all child-meshes of this node
  17570. * @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
  17571. * @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
  17572. * @returns an array of {BABYLON.AbstractMesh}
  17573. */
  17574. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17575. var results = [];
  17576. this._getDescendants(results, directDescendantsOnly, function (node) {
  17577. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17578. });
  17579. return results;
  17580. };
  17581. /**
  17582. * Get all child-transformNodes of this node
  17583. * @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
  17584. * @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
  17585. * @returns an array of {BABYLON.TransformNode}
  17586. */
  17587. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17588. var results = [];
  17589. this._getDescendants(results, directDescendantsOnly, function (node) {
  17590. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17591. });
  17592. return results;
  17593. };
  17594. /**
  17595. * Get all direct children of this node
  17596. * @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
  17597. * @returns an array of {BABYLON.Node}
  17598. */
  17599. Node.prototype.getChildren = function (predicate) {
  17600. return this.getDescendants(true, predicate);
  17601. };
  17602. /** @hidden */
  17603. Node.prototype._setReady = function (state) {
  17604. if (state === this._isReady) {
  17605. return;
  17606. }
  17607. if (!state) {
  17608. this._isReady = false;
  17609. return;
  17610. }
  17611. if (this.onReady) {
  17612. this.onReady(this);
  17613. }
  17614. this._isReady = true;
  17615. };
  17616. /**
  17617. * Get an animation by name
  17618. * @param name defines the name of the animation to look for
  17619. * @returns null if not found else the requested animation
  17620. */
  17621. Node.prototype.getAnimationByName = function (name) {
  17622. for (var i = 0; i < this.animations.length; i++) {
  17623. var animation = this.animations[i];
  17624. if (animation.name === name) {
  17625. return animation;
  17626. }
  17627. }
  17628. return null;
  17629. };
  17630. /**
  17631. * Creates an animation range for this node
  17632. * @param name defines the name of the range
  17633. * @param from defines the starting key
  17634. * @param to defines the end key
  17635. */
  17636. Node.prototype.createAnimationRange = function (name, from, to) {
  17637. // check name not already in use
  17638. if (!this._ranges[name]) {
  17639. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17640. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17641. if (this.animations[i]) {
  17642. this.animations[i].createRange(name, from, to);
  17643. }
  17644. }
  17645. }
  17646. };
  17647. /**
  17648. * Delete a specific animation range
  17649. * @param name defines the name of the range to delete
  17650. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17651. */
  17652. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17653. if (deleteFrames === void 0) { deleteFrames = true; }
  17654. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17655. if (this.animations[i]) {
  17656. this.animations[i].deleteRange(name, deleteFrames);
  17657. }
  17658. }
  17659. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17660. };
  17661. /**
  17662. * Get an animation range by name
  17663. * @param name defines the name of the animation range to look for
  17664. * @returns null if not found else the requested animation range
  17665. */
  17666. Node.prototype.getAnimationRange = function (name) {
  17667. return this._ranges[name];
  17668. };
  17669. /**
  17670. * Will start the animation sequence
  17671. * @param name defines the range frames for animation sequence
  17672. * @param loop defines if the animation should loop (false by default)
  17673. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17674. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17675. * @returns the object created for this animation. If range does not exist, it will return null
  17676. */
  17677. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17678. var range = this.getAnimationRange(name);
  17679. if (!range) {
  17680. return null;
  17681. }
  17682. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17683. };
  17684. /**
  17685. * Serialize animation ranges into a JSON compatible object
  17686. * @returns serialization object
  17687. */
  17688. Node.prototype.serializeAnimationRanges = function () {
  17689. var serializationRanges = [];
  17690. for (var name in this._ranges) {
  17691. var localRange = this._ranges[name];
  17692. if (!localRange) {
  17693. continue;
  17694. }
  17695. var range = {};
  17696. range.name = name;
  17697. range.from = localRange.from;
  17698. range.to = localRange.to;
  17699. serializationRanges.push(range);
  17700. }
  17701. return serializationRanges;
  17702. };
  17703. /**
  17704. * Computes the world matrix of the node
  17705. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17706. * @returns the world matrix
  17707. */
  17708. Node.prototype.computeWorldMatrix = function (force) {
  17709. return BABYLON.Matrix.Identity();
  17710. };
  17711. /**
  17712. * Releases resources associated with this node.
  17713. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17714. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17715. */
  17716. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17717. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17718. if (!doNotRecurse) {
  17719. var nodes = this.getDescendants(true);
  17720. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17721. var node = nodes_1[_i];
  17722. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17723. }
  17724. }
  17725. else {
  17726. var transformNodes = this.getChildTransformNodes(true);
  17727. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17728. var transformNode = transformNodes_1[_a];
  17729. transformNode.parent = null;
  17730. transformNode.computeWorldMatrix(true);
  17731. }
  17732. }
  17733. this.parent = null;
  17734. // Callback
  17735. this.onDisposeObservable.notifyObservers(this);
  17736. this.onDisposeObservable.clear();
  17737. // Behaviors
  17738. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17739. var behavior = _c[_b];
  17740. behavior.detach();
  17741. }
  17742. this._behaviors = [];
  17743. this._isDisposed = true;
  17744. };
  17745. /**
  17746. * Parse animation range data from a serialization object and store them into a given node
  17747. * @param node defines where to store the animation ranges
  17748. * @param parsedNode defines the serialization object to read data from
  17749. * @param scene defines the hosting scene
  17750. */
  17751. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17752. if (parsedNode.ranges) {
  17753. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17754. var data = parsedNode.ranges[index];
  17755. node.createAnimationRange(data.name, data.from, data.to);
  17756. }
  17757. }
  17758. };
  17759. Node._NodeConstructors = {};
  17760. __decorate([
  17761. BABYLON.serialize()
  17762. ], Node.prototype, "name", void 0);
  17763. __decorate([
  17764. BABYLON.serialize()
  17765. ], Node.prototype, "id", void 0);
  17766. __decorate([
  17767. BABYLON.serialize()
  17768. ], Node.prototype, "uniqueId", void 0);
  17769. __decorate([
  17770. BABYLON.serialize()
  17771. ], Node.prototype, "state", void 0);
  17772. __decorate([
  17773. BABYLON.serialize()
  17774. ], Node.prototype, "metadata", void 0);
  17775. return Node;
  17776. }());
  17777. BABYLON.Node = Node;
  17778. })(BABYLON || (BABYLON = {}));
  17779. //# sourceMappingURL=babylon.node.js.map
  17780. var BABYLON;
  17781. (function (BABYLON) {
  17782. var BoundingSphere = /** @class */ (function () {
  17783. /**
  17784. * Creates a new bounding sphere
  17785. * @param min defines the minimum vector (in local space)
  17786. * @param max defines the maximum vector (in local space)
  17787. */
  17788. function BoundingSphere(min, max) {
  17789. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17790. this.reConstruct(min, max);
  17791. }
  17792. /**
  17793. * Recreates the entire bounding sphere from scratch
  17794. * @param min defines the new minimum vector (in local space)
  17795. * @param max defines the new maximum vector (in local space)
  17796. */
  17797. BoundingSphere.prototype.reConstruct = function (min, max) {
  17798. this.minimum = min.clone();
  17799. this.maximum = max.clone();
  17800. var distance = BABYLON.Vector3.Distance(min, max);
  17801. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17802. this.radius = distance * 0.5;
  17803. this.centerWorld = BABYLON.Vector3.Zero();
  17804. this._update(BABYLON.Matrix.Identity());
  17805. };
  17806. /**
  17807. * Scale the current bounding sphere by applying a scale factor
  17808. * @param factor defines the scale factor to apply
  17809. * @returns the current bounding box
  17810. */
  17811. BoundingSphere.prototype.scale = function (factor) {
  17812. var newRadius = this.radius * factor;
  17813. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  17814. var min = this.center.subtract(newRadiusVector);
  17815. var max = this.center.add(newRadiusVector);
  17816. this.reConstruct(min, max);
  17817. return this;
  17818. };
  17819. // Methods
  17820. BoundingSphere.prototype._update = function (world) {
  17821. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17822. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17823. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17824. };
  17825. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17826. for (var i = 0; i < 6; i++) {
  17827. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17828. return false;
  17829. }
  17830. return true;
  17831. };
  17832. BoundingSphere.prototype.intersectsPoint = function (point) {
  17833. var x = this.centerWorld.x - point.x;
  17834. var y = this.centerWorld.y - point.y;
  17835. var z = this.centerWorld.z - point.z;
  17836. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17837. if (this.radiusWorld < distance)
  17838. return false;
  17839. return true;
  17840. };
  17841. // Statics
  17842. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17843. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17844. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17845. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17846. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17847. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17848. return false;
  17849. return true;
  17850. };
  17851. return BoundingSphere;
  17852. }());
  17853. BABYLON.BoundingSphere = BoundingSphere;
  17854. })(BABYLON || (BABYLON = {}));
  17855. //# sourceMappingURL=babylon.boundingSphere.js.map
  17856. var BABYLON;
  17857. (function (BABYLON) {
  17858. var BoundingBox = /** @class */ (function () {
  17859. /**
  17860. * Creates a new bounding box
  17861. * @param min defines the minimum vector (in local space)
  17862. * @param max defines the maximum vector (in local space)
  17863. */
  17864. function BoundingBox(min, max) {
  17865. this.vectorsWorld = new Array();
  17866. this.reConstruct(min, max);
  17867. }
  17868. // Methods
  17869. /**
  17870. * Recreates the entire bounding box from scratch
  17871. * @param min defines the new minimum vector (in local space)
  17872. * @param max defines the new maximum vector (in local space)
  17873. */
  17874. BoundingBox.prototype.reConstruct = function (min, max) {
  17875. this.minimum = min.clone();
  17876. this.maximum = max.clone();
  17877. // Bounding vectors
  17878. this.vectors = new Array();
  17879. this.vectors.push(this.minimum.clone());
  17880. this.vectors.push(this.maximum.clone());
  17881. this.vectors.push(this.minimum.clone());
  17882. this.vectors[2].x = this.maximum.x;
  17883. this.vectors.push(this.minimum.clone());
  17884. this.vectors[3].y = this.maximum.y;
  17885. this.vectors.push(this.minimum.clone());
  17886. this.vectors[4].z = this.maximum.z;
  17887. this.vectors.push(this.maximum.clone());
  17888. this.vectors[5].z = this.minimum.z;
  17889. this.vectors.push(this.maximum.clone());
  17890. this.vectors[6].x = this.minimum.x;
  17891. this.vectors.push(this.maximum.clone());
  17892. this.vectors[7].y = this.minimum.y;
  17893. // OBB
  17894. this.center = this.maximum.add(this.minimum).scale(0.5);
  17895. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17896. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17897. // World
  17898. for (var index = 0; index < this.vectors.length; index++) {
  17899. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17900. }
  17901. this.minimumWorld = BABYLON.Vector3.Zero();
  17902. this.maximumWorld = BABYLON.Vector3.Zero();
  17903. this.centerWorld = BABYLON.Vector3.Zero();
  17904. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17905. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17906. };
  17907. /**
  17908. * Scale the current bounding box by applying a scale factor
  17909. * @param factor defines the scale factor to apply
  17910. * @returns the current bounding box
  17911. */
  17912. BoundingBox.prototype.scale = function (factor) {
  17913. var diff = this.maximum.subtract(this.minimum);
  17914. var distance = diff.length() * factor;
  17915. diff.normalize();
  17916. var newRadius = diff.scale(distance / 2);
  17917. var min = this.center.subtract(newRadius);
  17918. var max = this.center.add(newRadius);
  17919. this.reConstruct(min, max);
  17920. return this;
  17921. };
  17922. BoundingBox.prototype.getWorldMatrix = function () {
  17923. return this._worldMatrix;
  17924. };
  17925. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17926. this._worldMatrix.copyFrom(matrix);
  17927. return this;
  17928. };
  17929. BoundingBox.prototype._update = function (world) {
  17930. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17931. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17932. for (var index = 0; index < this.vectors.length; index++) {
  17933. var v = this.vectorsWorld[index];
  17934. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17935. if (v.x < this.minimumWorld.x)
  17936. this.minimumWorld.x = v.x;
  17937. if (v.y < this.minimumWorld.y)
  17938. this.minimumWorld.y = v.y;
  17939. if (v.z < this.minimumWorld.z)
  17940. this.minimumWorld.z = v.z;
  17941. if (v.x > this.maximumWorld.x)
  17942. this.maximumWorld.x = v.x;
  17943. if (v.y > this.maximumWorld.y)
  17944. this.maximumWorld.y = v.y;
  17945. if (v.z > this.maximumWorld.z)
  17946. this.maximumWorld.z = v.z;
  17947. }
  17948. // Extend
  17949. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17950. this.extendSizeWorld.scaleInPlace(0.5);
  17951. // OBB
  17952. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17953. this.centerWorld.scaleInPlace(0.5);
  17954. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17955. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17956. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17957. this._worldMatrix = world;
  17958. };
  17959. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17960. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17961. };
  17962. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17963. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17964. };
  17965. BoundingBox.prototype.intersectsPoint = function (point) {
  17966. var delta = -BABYLON.Epsilon;
  17967. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17968. return false;
  17969. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17970. return false;
  17971. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17972. return false;
  17973. return true;
  17974. };
  17975. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17976. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17977. };
  17978. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17979. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17980. return false;
  17981. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17982. return false;
  17983. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17984. return false;
  17985. return true;
  17986. };
  17987. // Statics
  17988. BoundingBox.Intersects = function (box0, box1) {
  17989. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17990. return false;
  17991. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17992. return false;
  17993. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17994. return false;
  17995. return true;
  17996. };
  17997. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17998. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17999. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18000. return (num <= (sphereRadius * sphereRadius));
  18001. };
  18002. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18003. for (var p = 0; p < 6; p++) {
  18004. for (var i = 0; i < 8; i++) {
  18005. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18006. return false;
  18007. }
  18008. }
  18009. }
  18010. return true;
  18011. };
  18012. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18013. for (var p = 0; p < 6; p++) {
  18014. var inCount = 8;
  18015. for (var i = 0; i < 8; i++) {
  18016. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18017. --inCount;
  18018. }
  18019. else {
  18020. break;
  18021. }
  18022. }
  18023. if (inCount === 0)
  18024. return false;
  18025. }
  18026. return true;
  18027. };
  18028. return BoundingBox;
  18029. }());
  18030. BABYLON.BoundingBox = BoundingBox;
  18031. })(BABYLON || (BABYLON = {}));
  18032. //# sourceMappingURL=babylon.boundingBox.js.map
  18033. var BABYLON;
  18034. (function (BABYLON) {
  18035. var computeBoxExtents = function (axis, box) {
  18036. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18037. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18038. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18039. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18040. var r = r0 + r1 + r2;
  18041. return {
  18042. min: p - r,
  18043. max: p + r
  18044. };
  18045. };
  18046. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18047. var axisOverlap = function (axis, box0, box1) {
  18048. var result0 = computeBoxExtents(axis, box0);
  18049. var result1 = computeBoxExtents(axis, box1);
  18050. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18051. };
  18052. var BoundingInfo = /** @class */ (function () {
  18053. function BoundingInfo(minimum, maximum) {
  18054. this.minimum = minimum;
  18055. this.maximum = maximum;
  18056. this._isLocked = false;
  18057. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18058. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18059. }
  18060. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18061. get: function () {
  18062. return this._isLocked;
  18063. },
  18064. set: function (value) {
  18065. this._isLocked = value;
  18066. },
  18067. enumerable: true,
  18068. configurable: true
  18069. });
  18070. // Methods
  18071. BoundingInfo.prototype.update = function (world) {
  18072. if (this._isLocked) {
  18073. return;
  18074. }
  18075. this.boundingBox._update(world);
  18076. this.boundingSphere._update(world);
  18077. };
  18078. /**
  18079. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18080. * @param center New center of the bounding info
  18081. * @param extend New extend of the bounding info
  18082. */
  18083. BoundingInfo.prototype.centerOn = function (center, extend) {
  18084. this.minimum = center.subtract(extend);
  18085. this.maximum = center.add(extend);
  18086. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18087. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18088. return this;
  18089. };
  18090. /**
  18091. * Scale the current bounding info by applying a scale factor
  18092. * @param factor defines the scale factor to apply
  18093. * @returns the current bounding info
  18094. */
  18095. BoundingInfo.prototype.scale = function (factor) {
  18096. this.boundingBox.scale(factor);
  18097. this.boundingSphere.scale(factor);
  18098. return this;
  18099. };
  18100. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18101. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18102. return false;
  18103. return this.boundingBox.isInFrustum(frustumPlanes);
  18104. };
  18105. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18106. /**
  18107. * Gets the world distance between the min and max points of the bounding box
  18108. */
  18109. get: function () {
  18110. var boundingBox = this.boundingBox;
  18111. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18112. return size.length();
  18113. },
  18114. enumerable: true,
  18115. configurable: true
  18116. });
  18117. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18118. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18119. };
  18120. BoundingInfo.prototype._checkCollision = function (collider) {
  18121. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18122. };
  18123. BoundingInfo.prototype.intersectsPoint = function (point) {
  18124. if (!this.boundingSphere.centerWorld) {
  18125. return false;
  18126. }
  18127. if (!this.boundingSphere.intersectsPoint(point)) {
  18128. return false;
  18129. }
  18130. if (!this.boundingBox.intersectsPoint(point)) {
  18131. return false;
  18132. }
  18133. return true;
  18134. };
  18135. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18136. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18137. return false;
  18138. }
  18139. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18140. return false;
  18141. }
  18142. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18143. return false;
  18144. }
  18145. if (!precise) {
  18146. return true;
  18147. }
  18148. var box0 = this.boundingBox;
  18149. var box1 = boundingInfo.boundingBox;
  18150. if (!axisOverlap(box0.directions[0], box0, box1))
  18151. return false;
  18152. if (!axisOverlap(box0.directions[1], box0, box1))
  18153. return false;
  18154. if (!axisOverlap(box0.directions[2], box0, box1))
  18155. return false;
  18156. if (!axisOverlap(box1.directions[0], box0, box1))
  18157. return false;
  18158. if (!axisOverlap(box1.directions[1], box0, box1))
  18159. return false;
  18160. if (!axisOverlap(box1.directions[2], box0, box1))
  18161. return false;
  18162. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18163. return false;
  18164. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18165. return false;
  18166. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18167. return false;
  18168. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18169. return false;
  18170. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18171. return false;
  18172. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18173. return false;
  18174. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18175. return false;
  18176. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18177. return false;
  18178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18179. return false;
  18180. return true;
  18181. };
  18182. return BoundingInfo;
  18183. }());
  18184. BABYLON.BoundingInfo = BoundingInfo;
  18185. })(BABYLON || (BABYLON = {}));
  18186. //# sourceMappingURL=babylon.boundingInfo.js.map
  18187. var BABYLON;
  18188. (function (BABYLON) {
  18189. var TransformNode = /** @class */ (function (_super) {
  18190. __extends(TransformNode, _super);
  18191. function TransformNode(name, scene, isPure) {
  18192. if (scene === void 0) { scene = null; }
  18193. if (isPure === void 0) { isPure = true; }
  18194. var _this = _super.call(this, name, scene) || this;
  18195. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18196. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18197. _this._up = new BABYLON.Vector3(0, 1, 0);
  18198. _this._right = new BABYLON.Vector3(1, 0, 0);
  18199. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18200. // Properties
  18201. _this._rotation = BABYLON.Vector3.Zero();
  18202. _this._scaling = BABYLON.Vector3.One();
  18203. _this._isDirty = false;
  18204. /**
  18205. * Set the billboard mode. Default is 0.
  18206. *
  18207. * | Value | Type | Description |
  18208. * | --- | --- | --- |
  18209. * | 0 | BILLBOARDMODE_NONE | |
  18210. * | 1 | BILLBOARDMODE_X | |
  18211. * | 2 | BILLBOARDMODE_Y | |
  18212. * | 4 | BILLBOARDMODE_Z | |
  18213. * | 7 | BILLBOARDMODE_ALL | |
  18214. *
  18215. */
  18216. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18217. _this.scalingDeterminant = 1;
  18218. _this.infiniteDistance = false;
  18219. /**
  18220. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18221. * By default the system will update normals to compensate
  18222. */
  18223. _this.ignoreNonUniformScaling = false;
  18224. _this.position = BABYLON.Vector3.Zero();
  18225. _this._localWorld = BABYLON.Matrix.Zero();
  18226. _this._worldMatrix = BABYLON.Matrix.Zero();
  18227. _this._worldMatrixDeterminant = 0;
  18228. _this._absolutePosition = BABYLON.Vector3.Zero();
  18229. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18230. _this._postMultiplyPivotMatrix = false;
  18231. _this._isWorldMatrixFrozen = false;
  18232. /**
  18233. * An event triggered after the world matrix is updated
  18234. */
  18235. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18236. _this._nonUniformScaling = false;
  18237. if (isPure) {
  18238. _this.getScene().addTransformNode(_this);
  18239. }
  18240. return _this;
  18241. }
  18242. /**
  18243. * Gets a string idenfifying the name of the class
  18244. * @returns "TransformNode" string
  18245. */
  18246. TransformNode.prototype.getClassName = function () {
  18247. return "TransformNode";
  18248. };
  18249. Object.defineProperty(TransformNode.prototype, "rotation", {
  18250. /**
  18251. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18252. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18253. * Default : (0.0, 0.0, 0.0)
  18254. */
  18255. get: function () {
  18256. return this._rotation;
  18257. },
  18258. set: function (newRotation) {
  18259. this._rotation = newRotation;
  18260. },
  18261. enumerable: true,
  18262. configurable: true
  18263. });
  18264. Object.defineProperty(TransformNode.prototype, "scaling", {
  18265. /**
  18266. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18267. * Default : (1.0, 1.0, 1.0)
  18268. */
  18269. get: function () {
  18270. return this._scaling;
  18271. },
  18272. /**
  18273. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18274. * Default : (1.0, 1.0, 1.0)
  18275. */
  18276. set: function (newScaling) {
  18277. this._scaling = newScaling;
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18283. /**
  18284. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18285. * It's null by default.
  18286. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  18287. */
  18288. get: function () {
  18289. return this._rotationQuaternion;
  18290. },
  18291. set: function (quaternion) {
  18292. this._rotationQuaternion = quaternion;
  18293. //reset the rotation vector.
  18294. if (quaternion && this.rotation.length()) {
  18295. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18296. }
  18297. },
  18298. enumerable: true,
  18299. configurable: true
  18300. });
  18301. Object.defineProperty(TransformNode.prototype, "forward", {
  18302. /**
  18303. * The forward direction of that transform in world space.
  18304. */
  18305. get: function () {
  18306. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18307. },
  18308. enumerable: true,
  18309. configurable: true
  18310. });
  18311. Object.defineProperty(TransformNode.prototype, "up", {
  18312. /**
  18313. * The up direction of that transform in world space.
  18314. */
  18315. get: function () {
  18316. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18317. },
  18318. enumerable: true,
  18319. configurable: true
  18320. });
  18321. Object.defineProperty(TransformNode.prototype, "right", {
  18322. /**
  18323. * The right direction of that transform in world space.
  18324. */
  18325. get: function () {
  18326. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18327. },
  18328. enumerable: true,
  18329. configurable: true
  18330. });
  18331. /**
  18332. * Returns the latest update of the World matrix
  18333. * Returns a Matrix.
  18334. */
  18335. TransformNode.prototype.getWorldMatrix = function () {
  18336. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18337. this.computeWorldMatrix();
  18338. }
  18339. return this._worldMatrix;
  18340. };
  18341. /** @hidden */
  18342. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18343. return this._worldMatrixDeterminant;
  18344. };
  18345. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18346. /**
  18347. * Returns directly the latest state of the mesh World matrix.
  18348. * A Matrix is returned.
  18349. */
  18350. get: function () {
  18351. return this._worldMatrix;
  18352. },
  18353. enumerable: true,
  18354. configurable: true
  18355. });
  18356. /**
  18357. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18358. * Returns the TransformNode.
  18359. */
  18360. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18361. this._poseMatrix.copyFrom(matrix);
  18362. return this;
  18363. };
  18364. /**
  18365. * Returns the mesh Pose matrix.
  18366. * Returned object : Matrix
  18367. */
  18368. TransformNode.prototype.getPoseMatrix = function () {
  18369. return this._poseMatrix;
  18370. };
  18371. TransformNode.prototype._isSynchronized = function () {
  18372. if (this._isDirty) {
  18373. return false;
  18374. }
  18375. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18376. return false;
  18377. if (this._cache.pivotMatrixUpdated) {
  18378. return false;
  18379. }
  18380. if (this.infiniteDistance) {
  18381. return false;
  18382. }
  18383. if (!this._cache.position.equals(this.position))
  18384. return false;
  18385. if (this.rotationQuaternion) {
  18386. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18387. return false;
  18388. }
  18389. if (!this._cache.rotation.equals(this.rotation))
  18390. return false;
  18391. if (!this._cache.scaling.equals(this.scaling))
  18392. return false;
  18393. return true;
  18394. };
  18395. TransformNode.prototype._initCache = function () {
  18396. _super.prototype._initCache.call(this);
  18397. this._cache.localMatrixUpdated = false;
  18398. this._cache.position = BABYLON.Vector3.Zero();
  18399. this._cache.scaling = BABYLON.Vector3.Zero();
  18400. this._cache.rotation = BABYLON.Vector3.Zero();
  18401. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18402. this._cache.billboardMode = -1;
  18403. };
  18404. TransformNode.prototype.markAsDirty = function (property) {
  18405. if (property === "rotation") {
  18406. this.rotationQuaternion = null;
  18407. }
  18408. this._currentRenderId = Number.MAX_VALUE;
  18409. this._isDirty = true;
  18410. return this;
  18411. };
  18412. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18413. /**
  18414. * Returns the current mesh absolute position.
  18415. * Retuns a Vector3.
  18416. */
  18417. get: function () {
  18418. return this._absolutePosition;
  18419. },
  18420. enumerable: true,
  18421. configurable: true
  18422. });
  18423. /**
  18424. * Sets a new matrix to apply before all other transformation
  18425. * @param matrix defines the transform matrix
  18426. * @returns the current TransformNode
  18427. */
  18428. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18429. return this.setPivotMatrix(matrix, false);
  18430. };
  18431. /**
  18432. * Sets a new pivot matrix to the current node
  18433. * @param matrix defines the new pivot matrix to use
  18434. * @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
  18435. * @returns the current TransformNode
  18436. */
  18437. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18438. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18439. this._pivotMatrix = matrix.clone();
  18440. this._cache.pivotMatrixUpdated = true;
  18441. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18442. if (this._postMultiplyPivotMatrix) {
  18443. if (!this._pivotMatrixInverse) {
  18444. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18445. }
  18446. else {
  18447. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18448. }
  18449. }
  18450. return this;
  18451. };
  18452. /**
  18453. * Returns the mesh pivot matrix.
  18454. * Default : Identity.
  18455. * A Matrix is returned.
  18456. */
  18457. TransformNode.prototype.getPivotMatrix = function () {
  18458. return this._pivotMatrix;
  18459. };
  18460. /**
  18461. * Prevents the World matrix to be computed any longer.
  18462. * Returns the TransformNode.
  18463. */
  18464. TransformNode.prototype.freezeWorldMatrix = function () {
  18465. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18466. this.computeWorldMatrix(true);
  18467. this._isWorldMatrixFrozen = true;
  18468. return this;
  18469. };
  18470. /**
  18471. * Allows back the World matrix computation.
  18472. * Returns the TransformNode.
  18473. */
  18474. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18475. this._isWorldMatrixFrozen = false;
  18476. this.computeWorldMatrix(true);
  18477. return this;
  18478. };
  18479. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18480. /**
  18481. * True if the World matrix has been frozen.
  18482. * Returns a boolean.
  18483. */
  18484. get: function () {
  18485. return this._isWorldMatrixFrozen;
  18486. },
  18487. enumerable: true,
  18488. configurable: true
  18489. });
  18490. /**
  18491. * Retuns the mesh absolute position in the World.
  18492. * Returns a Vector3.
  18493. */
  18494. TransformNode.prototype.getAbsolutePosition = function () {
  18495. this.computeWorldMatrix();
  18496. return this._absolutePosition;
  18497. };
  18498. /**
  18499. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18500. * Returns the TransformNode.
  18501. */
  18502. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18503. if (!absolutePosition) {
  18504. return this;
  18505. }
  18506. var absolutePositionX;
  18507. var absolutePositionY;
  18508. var absolutePositionZ;
  18509. if (absolutePosition.x === undefined) {
  18510. if (arguments.length < 3) {
  18511. return this;
  18512. }
  18513. absolutePositionX = arguments[0];
  18514. absolutePositionY = arguments[1];
  18515. absolutePositionZ = arguments[2];
  18516. }
  18517. else {
  18518. absolutePositionX = absolutePosition.x;
  18519. absolutePositionY = absolutePosition.y;
  18520. absolutePositionZ = absolutePosition.z;
  18521. }
  18522. if (this.parent) {
  18523. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18524. invertParentWorldMatrix.invert();
  18525. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18526. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18527. }
  18528. else {
  18529. this.position.x = absolutePositionX;
  18530. this.position.y = absolutePositionY;
  18531. this.position.z = absolutePositionZ;
  18532. }
  18533. return this;
  18534. };
  18535. /**
  18536. * Sets the mesh position in its local space.
  18537. * Returns the TransformNode.
  18538. */
  18539. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18540. this.computeWorldMatrix();
  18541. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18542. return this;
  18543. };
  18544. /**
  18545. * Returns the mesh position in the local space from the current World matrix values.
  18546. * Returns a new Vector3.
  18547. */
  18548. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18549. this.computeWorldMatrix();
  18550. var invLocalWorldMatrix = this._localWorld.clone();
  18551. invLocalWorldMatrix.invert();
  18552. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18553. };
  18554. /**
  18555. * Translates the mesh along the passed Vector3 in its local space.
  18556. * Returns the TransformNode.
  18557. */
  18558. TransformNode.prototype.locallyTranslate = function (vector3) {
  18559. this.computeWorldMatrix(true);
  18560. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18561. return this;
  18562. };
  18563. /**
  18564. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18565. * @param targetPoint the position (must be in same space as current mesh) to look at
  18566. * @param yawCor optional yaw (y-axis) correction in radians
  18567. * @param pitchCor optional pitch (x-axis) correction in radians
  18568. * @param rollCor optional roll (z-axis) correction in radians
  18569. * @param space the choosen space of the target
  18570. * @returns the TransformNode.
  18571. */
  18572. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18573. if (yawCor === void 0) { yawCor = 0; }
  18574. if (pitchCor === void 0) { pitchCor = 0; }
  18575. if (rollCor === void 0) { rollCor = 0; }
  18576. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18577. var dv = TransformNode._lookAtVectorCache;
  18578. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18579. targetPoint.subtractToRef(pos, dv);
  18580. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18581. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18582. var pitch = Math.atan2(dv.y, len);
  18583. if (this.rotationQuaternion) {
  18584. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18585. }
  18586. else {
  18587. this.rotation.x = pitch + pitchCor;
  18588. this.rotation.y = yaw + yawCor;
  18589. this.rotation.z = rollCor;
  18590. }
  18591. return this;
  18592. };
  18593. /**
  18594. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18595. * This Vector3 is expressed in the World space.
  18596. */
  18597. TransformNode.prototype.getDirection = function (localAxis) {
  18598. var result = BABYLON.Vector3.Zero();
  18599. this.getDirectionToRef(localAxis, result);
  18600. return result;
  18601. };
  18602. /**
  18603. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18604. * localAxis is expressed in the mesh local space.
  18605. * result is computed in the Wordl space from the mesh World matrix.
  18606. * Returns the TransformNode.
  18607. */
  18608. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18609. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18610. return this;
  18611. };
  18612. /**
  18613. * Sets a new pivot point to the current node
  18614. * @param point defines the new pivot point to use
  18615. * @param space defines if the point is in world or local space (local by default)
  18616. * @returns the current TransformNode
  18617. */
  18618. TransformNode.prototype.setPivotPoint = function (point, space) {
  18619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18620. if (this.getScene().getRenderId() == 0) {
  18621. this.computeWorldMatrix(true);
  18622. }
  18623. var wm = this.getWorldMatrix();
  18624. if (space == BABYLON.Space.WORLD) {
  18625. var tmat = BABYLON.Tmp.Matrix[0];
  18626. wm.invertToRef(tmat);
  18627. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18628. }
  18629. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18630. };
  18631. /**
  18632. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18633. */
  18634. TransformNode.prototype.getPivotPoint = function () {
  18635. var point = BABYLON.Vector3.Zero();
  18636. this.getPivotPointToRef(point);
  18637. return point;
  18638. };
  18639. /**
  18640. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18641. * Returns the TransformNode.
  18642. */
  18643. TransformNode.prototype.getPivotPointToRef = function (result) {
  18644. result.x = -this._pivotMatrix.m[12];
  18645. result.y = -this._pivotMatrix.m[13];
  18646. result.z = -this._pivotMatrix.m[14];
  18647. return this;
  18648. };
  18649. /**
  18650. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18651. */
  18652. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18653. var point = BABYLON.Vector3.Zero();
  18654. this.getAbsolutePivotPointToRef(point);
  18655. return point;
  18656. };
  18657. /**
  18658. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18659. * Returns the TransformNode.
  18660. */
  18661. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18662. result.x = this._pivotMatrix.m[12];
  18663. result.y = this._pivotMatrix.m[13];
  18664. result.z = this._pivotMatrix.m[14];
  18665. this.getPivotPointToRef(result);
  18666. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18667. return this;
  18668. };
  18669. /**
  18670. * Defines the passed node as the parent of the current node.
  18671. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18672. * Returns the TransformNode.
  18673. */
  18674. TransformNode.prototype.setParent = function (node) {
  18675. if (!node && !this.parent) {
  18676. return this;
  18677. }
  18678. if (!node) {
  18679. var rotation = BABYLON.Tmp.Quaternion[0];
  18680. var position = BABYLON.Tmp.Vector3[0];
  18681. var scale = BABYLON.Tmp.Vector3[1];
  18682. if (this.parent && this.parent.computeWorldMatrix) {
  18683. this.parent.computeWorldMatrix(true);
  18684. }
  18685. this.computeWorldMatrix(true);
  18686. this.getWorldMatrix().decompose(scale, rotation, position);
  18687. if (this.rotationQuaternion) {
  18688. this.rotationQuaternion.copyFrom(rotation);
  18689. }
  18690. else {
  18691. rotation.toEulerAnglesToRef(this.rotation);
  18692. }
  18693. this.scaling.x = scale.x;
  18694. this.scaling.y = scale.y;
  18695. this.scaling.z = scale.z;
  18696. this.position.x = position.x;
  18697. this.position.y = position.y;
  18698. this.position.z = position.z;
  18699. }
  18700. else {
  18701. var rotation = BABYLON.Tmp.Quaternion[0];
  18702. var position = BABYLON.Tmp.Vector3[0];
  18703. var scale = BABYLON.Tmp.Vector3[1];
  18704. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18705. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18706. this.computeWorldMatrix(true);
  18707. node.computeWorldMatrix(true);
  18708. node.getWorldMatrix().invertToRef(invParentMatrix);
  18709. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18710. diffMatrix.decompose(scale, rotation, position);
  18711. if (this.rotationQuaternion) {
  18712. this.rotationQuaternion.copyFrom(rotation);
  18713. }
  18714. else {
  18715. rotation.toEulerAnglesToRef(this.rotation);
  18716. }
  18717. this.position.x = position.x;
  18718. this.position.y = position.y;
  18719. this.position.z = position.z;
  18720. this.scaling.x = scale.x;
  18721. this.scaling.y = scale.y;
  18722. this.scaling.z = scale.z;
  18723. }
  18724. this.parent = node;
  18725. return this;
  18726. };
  18727. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18728. get: function () {
  18729. return this._nonUniformScaling;
  18730. },
  18731. enumerable: true,
  18732. configurable: true
  18733. });
  18734. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18735. if (this._nonUniformScaling === value) {
  18736. return false;
  18737. }
  18738. this._nonUniformScaling = value;
  18739. return true;
  18740. };
  18741. /**
  18742. * Attach the current TransformNode to another TransformNode associated with a bone
  18743. * @param bone Bone affecting the TransformNode
  18744. * @param affectedTransformNode TransformNode associated with the bone
  18745. */
  18746. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18747. this._transformToBoneReferal = affectedTransformNode;
  18748. this.parent = bone;
  18749. if (bone.getWorldMatrix().determinant() < 0) {
  18750. this.scalingDeterminant *= -1;
  18751. }
  18752. return this;
  18753. };
  18754. TransformNode.prototype.detachFromBone = function () {
  18755. if (!this.parent) {
  18756. return this;
  18757. }
  18758. if (this.parent.getWorldMatrix().determinant() < 0) {
  18759. this.scalingDeterminant *= -1;
  18760. }
  18761. this._transformToBoneReferal = null;
  18762. this.parent = null;
  18763. return this;
  18764. };
  18765. /**
  18766. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18767. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18768. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18769. * The passed axis is also normalized.
  18770. * Returns the TransformNode.
  18771. */
  18772. TransformNode.prototype.rotate = function (axis, amount, space) {
  18773. axis.normalize();
  18774. if (!this.rotationQuaternion) {
  18775. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18776. this.rotation = BABYLON.Vector3.Zero();
  18777. }
  18778. var rotationQuaternion;
  18779. if (!space || space === BABYLON.Space.LOCAL) {
  18780. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18781. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18782. }
  18783. else {
  18784. if (this.parent) {
  18785. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18786. invertParentWorldMatrix.invert();
  18787. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18788. }
  18789. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18790. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18791. }
  18792. return this;
  18793. };
  18794. /**
  18795. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18796. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18797. * The passed axis is also normalized.
  18798. * Returns the TransformNode.
  18799. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18800. */
  18801. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18802. axis.normalize();
  18803. if (!this.rotationQuaternion) {
  18804. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18805. this.rotation.copyFromFloats(0, 0, 0);
  18806. }
  18807. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18808. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18809. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18810. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18811. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18812. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18813. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18814. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18815. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18816. return this;
  18817. };
  18818. /**
  18819. * Translates the mesh along the axis vector for the passed distance in the given space.
  18820. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18821. * Returns the TransformNode.
  18822. */
  18823. TransformNode.prototype.translate = function (axis, distance, space) {
  18824. var displacementVector = axis.scale(distance);
  18825. if (!space || space === BABYLON.Space.LOCAL) {
  18826. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18827. this.setPositionWithLocalVector(tempV3);
  18828. }
  18829. else {
  18830. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18831. }
  18832. return this;
  18833. };
  18834. /**
  18835. * Adds a rotation step to the mesh current rotation.
  18836. * x, y, z are Euler angles expressed in radians.
  18837. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18838. * This means this rotation is made in the mesh local space only.
  18839. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18840. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18841. * ```javascript
  18842. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18843. * ```
  18844. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18845. * 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.
  18846. * Returns the TransformNode.
  18847. */
  18848. TransformNode.prototype.addRotation = function (x, y, z) {
  18849. var rotationQuaternion;
  18850. if (this.rotationQuaternion) {
  18851. rotationQuaternion = this.rotationQuaternion;
  18852. }
  18853. else {
  18854. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18855. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18856. }
  18857. var accumulation = BABYLON.Tmp.Quaternion[0];
  18858. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18859. rotationQuaternion.multiplyInPlace(accumulation);
  18860. if (!this.rotationQuaternion) {
  18861. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18862. }
  18863. return this;
  18864. };
  18865. /**
  18866. * Computes the mesh World matrix and returns it.
  18867. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18868. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18869. * If the parameter `force`is set to `true`, the actual computation is done.
  18870. * Returns the mesh World Matrix.
  18871. */
  18872. TransformNode.prototype.computeWorldMatrix = function (force) {
  18873. if (this._isWorldMatrixFrozen) {
  18874. return this._worldMatrix;
  18875. }
  18876. if (!force && this.isSynchronized(true)) {
  18877. this._currentRenderId = this.getScene().getRenderId();
  18878. return this._worldMatrix;
  18879. }
  18880. this._cache.position.copyFrom(this.position);
  18881. this._cache.scaling.copyFrom(this.scaling);
  18882. this._cache.pivotMatrixUpdated = false;
  18883. this._cache.billboardMode = this.billboardMode;
  18884. this._currentRenderId = this.getScene().getRenderId();
  18885. this._childRenderId = this.getScene().getRenderId();
  18886. this._isDirty = false;
  18887. // Scaling
  18888. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18889. // Rotation
  18890. //rotate, if quaternion is set and rotation was used
  18891. if (this.rotationQuaternion) {
  18892. var len = this.rotation.length();
  18893. if (len) {
  18894. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18895. this.rotation.copyFromFloats(0, 0, 0);
  18896. }
  18897. }
  18898. if (this.rotationQuaternion) {
  18899. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18900. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18901. }
  18902. else {
  18903. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18904. this._cache.rotation.copyFrom(this.rotation);
  18905. }
  18906. // Translation
  18907. var camera = this.getScene().activeCamera;
  18908. if (this.infiniteDistance && !this.parent && camera) {
  18909. var cameraWorldMatrix = camera.getWorldMatrix();
  18910. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18911. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18912. }
  18913. else {
  18914. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18915. }
  18916. // Composing transformations
  18917. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18918. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18919. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18920. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18921. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18922. // Need to decompose each rotation here
  18923. var currentPosition = BABYLON.Tmp.Vector3[3];
  18924. if (this.parent && this.parent.getWorldMatrix) {
  18925. if (this._transformToBoneReferal) {
  18926. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18927. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18928. }
  18929. else {
  18930. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18931. }
  18932. }
  18933. else {
  18934. currentPosition.copyFrom(this.position);
  18935. }
  18936. currentPosition.subtractInPlace(camera.globalPosition);
  18937. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18938. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18939. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18940. }
  18941. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18942. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18943. }
  18944. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18945. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18946. }
  18947. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18948. }
  18949. else {
  18950. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18951. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18952. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18953. }
  18954. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18955. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18956. }
  18957. // Post multiply inverse of pivotMatrix
  18958. if (this._postMultiplyPivotMatrix) {
  18959. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  18960. }
  18961. // Local world
  18962. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18963. // Parent
  18964. if (this.parent && this.parent.getWorldMatrix) {
  18965. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18966. if (this._transformToBoneReferal) {
  18967. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18968. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18969. }
  18970. else {
  18971. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18972. }
  18973. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18974. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18975. this._worldMatrix.copyFrom(this._localWorld);
  18976. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18977. }
  18978. else {
  18979. if (this._transformToBoneReferal) {
  18980. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18981. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18982. }
  18983. else {
  18984. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18985. }
  18986. }
  18987. this._markSyncedWithParent();
  18988. }
  18989. else {
  18990. this._worldMatrix.copyFrom(this._localWorld);
  18991. }
  18992. // Normal matrix
  18993. if (!this.ignoreNonUniformScaling) {
  18994. if (this.scaling.isNonUniform) {
  18995. this._updateNonUniformScalingState(true);
  18996. }
  18997. else if (this.parent && this.parent._nonUniformScaling) {
  18998. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18999. }
  19000. else {
  19001. this._updateNonUniformScalingState(false);
  19002. }
  19003. }
  19004. else {
  19005. this._updateNonUniformScalingState(false);
  19006. }
  19007. this._afterComputeWorldMatrix();
  19008. // Absolute position
  19009. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19010. // Callbacks
  19011. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19012. if (!this._poseMatrix) {
  19013. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19014. }
  19015. // Cache the determinant
  19016. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19017. return this._worldMatrix;
  19018. };
  19019. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19020. };
  19021. /**
  19022. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19023. * @param func: callback function to add
  19024. *
  19025. * Returns the TransformNode.
  19026. */
  19027. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19028. this.onAfterWorldMatrixUpdateObservable.add(func);
  19029. return this;
  19030. };
  19031. /**
  19032. * Removes a registered callback function.
  19033. * Returns the TransformNode.
  19034. */
  19035. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19036. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19037. return this;
  19038. };
  19039. /**
  19040. * Clone the current transform node
  19041. * Returns the new transform node
  19042. * @param name Name of the new clone
  19043. * @param newParent New parent for the clone
  19044. * @param doNotCloneChildren Do not clone children hierarchy
  19045. */
  19046. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19047. var _this = this;
  19048. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19049. result.name = name;
  19050. result.id = name;
  19051. if (newParent) {
  19052. result.parent = newParent;
  19053. }
  19054. if (!doNotCloneChildren) {
  19055. // Children
  19056. var directDescendants = this.getDescendants(true);
  19057. for (var index = 0; index < directDescendants.length; index++) {
  19058. var child = directDescendants[index];
  19059. if (child.clone) {
  19060. child.clone(name + "." + child.name, result);
  19061. }
  19062. }
  19063. }
  19064. return result;
  19065. };
  19066. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19067. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19068. serializationObject.type = this.getClassName();
  19069. // Parent
  19070. if (this.parent) {
  19071. serializationObject.parentId = this.parent.id;
  19072. }
  19073. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19074. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19075. }
  19076. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19077. serializationObject.isEnabled = this.isEnabled();
  19078. // Parent
  19079. if (this.parent) {
  19080. serializationObject.parentId = this.parent.id;
  19081. }
  19082. return serializationObject;
  19083. };
  19084. // Statics
  19085. /**
  19086. * Returns a new TransformNode object parsed from the source provided.
  19087. * The parameter `parsedMesh` is the source.
  19088. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19089. */
  19090. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19091. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19092. if (BABYLON.Tags) {
  19093. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19094. }
  19095. if (parsedTransformNode.localMatrix) {
  19096. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19097. }
  19098. else if (parsedTransformNode.pivotMatrix) {
  19099. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19100. }
  19101. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19102. // Parent
  19103. if (parsedTransformNode.parentId) {
  19104. transformNode._waitingParentId = parsedTransformNode.parentId;
  19105. }
  19106. return transformNode;
  19107. };
  19108. /**
  19109. * Releases resources associated with this transform node.
  19110. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19111. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19112. */
  19113. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19114. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19115. // Animations
  19116. this.getScene().stopAnimation(this);
  19117. // Remove from scene
  19118. this.getScene().removeTransformNode(this);
  19119. this.onAfterWorldMatrixUpdateObservable.clear();
  19120. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19121. };
  19122. // Statics
  19123. TransformNode.BILLBOARDMODE_NONE = 0;
  19124. TransformNode.BILLBOARDMODE_X = 1;
  19125. TransformNode.BILLBOARDMODE_Y = 2;
  19126. TransformNode.BILLBOARDMODE_Z = 4;
  19127. TransformNode.BILLBOARDMODE_ALL = 7;
  19128. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19129. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19130. __decorate([
  19131. BABYLON.serializeAsVector3()
  19132. ], TransformNode.prototype, "_rotation", void 0);
  19133. __decorate([
  19134. BABYLON.serializeAsQuaternion()
  19135. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19136. __decorate([
  19137. BABYLON.serializeAsVector3()
  19138. ], TransformNode.prototype, "_scaling", void 0);
  19139. __decorate([
  19140. BABYLON.serialize()
  19141. ], TransformNode.prototype, "billboardMode", void 0);
  19142. __decorate([
  19143. BABYLON.serialize()
  19144. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19145. __decorate([
  19146. BABYLON.serialize()
  19147. ], TransformNode.prototype, "infiniteDistance", void 0);
  19148. __decorate([
  19149. BABYLON.serialize()
  19150. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19151. __decorate([
  19152. BABYLON.serializeAsVector3()
  19153. ], TransformNode.prototype, "position", void 0);
  19154. return TransformNode;
  19155. }(BABYLON.Node));
  19156. BABYLON.TransformNode = TransformNode;
  19157. })(BABYLON || (BABYLON = {}));
  19158. //# sourceMappingURL=babylon.transformNode.js.map
  19159. var BABYLON;
  19160. (function (BABYLON) {
  19161. /**
  19162. * Class used to store all common mesh properties
  19163. */
  19164. var AbstractMesh = /** @class */ (function (_super) {
  19165. __extends(AbstractMesh, _super);
  19166. // Constructor
  19167. /**
  19168. * Creates a new AbstractMesh
  19169. * @param name defines the name of the mesh
  19170. * @param scene defines the hosting scene
  19171. */
  19172. function AbstractMesh(name, scene) {
  19173. if (scene === void 0) { scene = null; }
  19174. var _this = _super.call(this, name, scene, false) || this;
  19175. _this._facetNb = 0; // facet number
  19176. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19177. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19178. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19179. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19180. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19181. _this._subDiv = {
  19182. max: 1,
  19183. X: 1,
  19184. Y: 1,
  19185. Z: 1
  19186. };
  19187. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19188. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19189. // Events
  19190. /**
  19191. * An event triggered when this mesh collides with another one
  19192. */
  19193. _this.onCollideObservable = new BABYLON.Observable();
  19194. /**
  19195. * An event triggered when the collision's position changes
  19196. */
  19197. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19198. /**
  19199. * An event triggered when material is changed
  19200. */
  19201. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19202. // Properties
  19203. /**
  19204. * Gets or sets the orientation for POV movement & rotation
  19205. */
  19206. _this.definedFacingForward = true;
  19207. /**
  19208. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19209. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19210. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  19211. * @see http://doc.babylonjs.com/features/occlusionquery
  19212. */
  19213. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19214. /**
  19215. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  19216. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19217. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19218. * * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  19219. * @see http://doc.babylonjs.com/features/occlusionquery
  19220. */
  19221. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19222. /**
  19223. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  19224. * The default value is -1 which means don't break the query and wait till the result
  19225. * @see http://doc.babylonjs.com/features/occlusionquery
  19226. */
  19227. _this.occlusionRetryCount = -1;
  19228. /** @hidden */
  19229. _this._occlusionInternalRetryCounter = 0;
  19230. /** @hidden */
  19231. _this._isOccluded = false;
  19232. /** @hidden */
  19233. _this._isOcclusionQueryInProgress = false;
  19234. _this._visibility = 1.0;
  19235. /** Gets or sets the alpha index used to sort transparent meshes
  19236. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19237. */
  19238. _this.alphaIndex = Number.MAX_VALUE;
  19239. /**
  19240. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19241. */
  19242. _this.isVisible = true;
  19243. /**
  19244. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19245. */
  19246. _this.isPickable = true;
  19247. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19248. _this.showSubMeshesBoundingBox = false;
  19249. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19250. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19251. */
  19252. _this.isBlocker = false;
  19253. /**
  19254. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19255. */
  19256. _this.enablePointerMoveEvents = false;
  19257. /**
  19258. * Specifies the rendering group id for this mesh (0 by default)
  19259. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19260. */
  19261. _this.renderingGroupId = 0;
  19262. _this._receiveShadows = false;
  19263. /**
  19264. * Gets or sets a boolean indicating if the outline must be rendered as well
  19265. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19266. */
  19267. _this.renderOutline = false;
  19268. /** Defines color to use when rendering outline */
  19269. _this.outlineColor = BABYLON.Color3.Red();
  19270. /** Define width to use when rendering outline */
  19271. _this.outlineWidth = 0.02;
  19272. /**
  19273. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19274. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19275. */
  19276. _this.renderOverlay = false;
  19277. /** Defines color to use when rendering overlay */
  19278. _this.overlayColor = BABYLON.Color3.Red();
  19279. /** Defines alpha to use when rendering overlay */
  19280. _this.overlayAlpha = 0.5;
  19281. _this._hasVertexAlpha = false;
  19282. _this._useVertexColors = true;
  19283. _this._computeBonesUsingShaders = true;
  19284. _this._numBoneInfluencers = 4;
  19285. _this._applyFog = true;
  19286. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19287. _this.useOctreeForRenderingSelection = true;
  19288. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19289. _this.useOctreeForPicking = true;
  19290. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19291. _this.useOctreeForCollisions = true;
  19292. _this._layerMask = 0x0FFFFFFF;
  19293. /**
  19294. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19295. */
  19296. _this.alwaysSelectAsActiveMesh = false;
  19297. /**
  19298. * Gets or sets the current action manager
  19299. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19300. */
  19301. _this.actionManager = null;
  19302. /**
  19303. * Gets or sets impostor used for physic simulation
  19304. * @see http://doc.babylonjs.com/features/physics_engine
  19305. */
  19306. _this.physicsImpostor = null;
  19307. // Collisions
  19308. _this._checkCollisions = false;
  19309. _this._collisionMask = -1;
  19310. _this._collisionGroup = -1;
  19311. /**
  19312. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19313. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19314. */
  19315. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19316. /**
  19317. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19318. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19319. */
  19320. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19321. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19322. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19323. // Edges
  19324. /**
  19325. * Defines edge width used when edgesRenderer is enabled
  19326. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19327. */
  19328. _this.edgesWidth = 1;
  19329. /**
  19330. * Defines edge color used when edgesRenderer is enabled
  19331. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19332. */
  19333. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19334. // Cache
  19335. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19336. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19337. /** @hidden */
  19338. _this._renderId = 0;
  19339. /** @hidden */
  19340. _this._intersectionsInProgress = new Array();
  19341. /** @hidden */
  19342. _this._unIndexed = false;
  19343. /** @hidden */
  19344. _this._lightSources = new Array();
  19345. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19346. if (collidedMesh === void 0) { collidedMesh = null; }
  19347. //TODO move this to the collision coordinator!
  19348. if (_this.getScene().workerCollisions)
  19349. newPosition.multiplyInPlace(_this._collider._radius);
  19350. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19351. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19352. _this.position.addInPlace(_this._diffPositionForCollisions);
  19353. }
  19354. if (collidedMesh) {
  19355. _this.onCollideObservable.notifyObservers(collidedMesh);
  19356. }
  19357. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19358. };
  19359. _this.getScene().addMesh(_this);
  19360. _this._resyncLightSources();
  19361. return _this;
  19362. }
  19363. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19364. /**
  19365. * No billboard
  19366. */
  19367. get: function () {
  19368. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19369. },
  19370. enumerable: true,
  19371. configurable: true
  19372. });
  19373. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19374. /** Billboard on X axis */
  19375. get: function () {
  19376. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19382. /** Billboard on Y axis */
  19383. get: function () {
  19384. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19390. /** Billboard on Z axis */
  19391. get: function () {
  19392. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19393. },
  19394. enumerable: true,
  19395. configurable: true
  19396. });
  19397. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19398. /** Billboard on all axes */
  19399. get: function () {
  19400. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19401. },
  19402. enumerable: true,
  19403. configurable: true
  19404. });
  19405. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19406. /**
  19407. * Gets the number of facets in the mesh
  19408. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19409. */
  19410. get: function () {
  19411. return this._facetNb;
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19417. /**
  19418. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19419. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19420. */
  19421. get: function () {
  19422. return this._partitioningSubdivisions;
  19423. },
  19424. set: function (nb) {
  19425. this._partitioningSubdivisions = nb;
  19426. },
  19427. enumerable: true,
  19428. configurable: true
  19429. });
  19430. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19431. /**
  19432. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19433. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19434. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19435. */
  19436. get: function () {
  19437. return this._partitioningBBoxRatio;
  19438. },
  19439. set: function (ratio) {
  19440. this._partitioningBBoxRatio = ratio;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19446. /**
  19447. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19448. * Works only for updatable meshes.
  19449. * Doesn't work with multi-materials
  19450. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19451. */
  19452. get: function () {
  19453. return this._facetDepthSort;
  19454. },
  19455. set: function (sort) {
  19456. this._facetDepthSort = sort;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19462. /**
  19463. * The location (Vector3) where the facet depth sort must be computed from.
  19464. * By default, the active camera position.
  19465. * Used only when facet depth sort is enabled
  19466. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19467. */
  19468. get: function () {
  19469. return this._facetDepthSortFrom;
  19470. },
  19471. set: function (location) {
  19472. this._facetDepthSortFrom = location;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19478. /**
  19479. * gets a boolean indicating if facetData is enabled
  19480. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19481. */
  19482. get: function () {
  19483. return this._facetDataEnabled;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. /** @hidden */
  19489. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19490. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19491. return false;
  19492. }
  19493. this._markSubMeshesAsMiscDirty();
  19494. return true;
  19495. };
  19496. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19497. /** Set a function to call when this mesh collides with another one */
  19498. set: function (callback) {
  19499. if (this._onCollideObserver) {
  19500. this.onCollideObservable.remove(this._onCollideObserver);
  19501. }
  19502. this._onCollideObserver = this.onCollideObservable.add(callback);
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19508. /** Set a function to call when the collision's position changes */
  19509. set: function (callback) {
  19510. if (this._onCollisionPositionChangeObserver) {
  19511. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19512. }
  19513. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19519. /**
  19520. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19521. * @see http://doc.babylonjs.com/features/occlusionquery
  19522. */
  19523. get: function () {
  19524. return this._isOccluded;
  19525. },
  19526. set: function (value) {
  19527. this._isOccluded = value;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19533. /**
  19534. * Flag to check the progress status of the query
  19535. * @see http://doc.babylonjs.com/features/occlusionquery
  19536. */
  19537. get: function () {
  19538. return this._isOcclusionQueryInProgress;
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19544. /**
  19545. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19546. */
  19547. get: function () {
  19548. return this._visibility;
  19549. },
  19550. /**
  19551. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19552. */
  19553. set: function (value) {
  19554. if (this._visibility === value) {
  19555. return;
  19556. }
  19557. this._visibility = value;
  19558. this._markSubMeshesAsMiscDirty();
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. Object.defineProperty(AbstractMesh.prototype, "material", {
  19564. /** Gets or sets current material */
  19565. get: function () {
  19566. return this._material;
  19567. },
  19568. set: function (value) {
  19569. if (this._material === value) {
  19570. return;
  19571. }
  19572. this._material = value;
  19573. if (this.onMaterialChangedObservable.hasObservers) {
  19574. this.onMaterialChangedObservable.notifyObservers(this);
  19575. }
  19576. if (!this.subMeshes) {
  19577. return;
  19578. }
  19579. this._unBindEffect();
  19580. },
  19581. enumerable: true,
  19582. configurable: true
  19583. });
  19584. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19585. /**
  19586. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19587. * @see http://doc.babylonjs.com/babylon101/shadows
  19588. */
  19589. get: function () {
  19590. return this._receiveShadows;
  19591. },
  19592. set: function (value) {
  19593. if (this._receiveShadows === value) {
  19594. return;
  19595. }
  19596. this._receiveShadows = value;
  19597. this._markSubMeshesAsLightDirty();
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19603. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19604. get: function () {
  19605. return this._hasVertexAlpha;
  19606. },
  19607. set: function (value) {
  19608. if (this._hasVertexAlpha === value) {
  19609. return;
  19610. }
  19611. this._hasVertexAlpha = value;
  19612. this._markSubMeshesAsAttributesDirty();
  19613. this._markSubMeshesAsMiscDirty();
  19614. },
  19615. enumerable: true,
  19616. configurable: true
  19617. });
  19618. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19619. /** 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) */
  19620. get: function () {
  19621. return this._useVertexColors;
  19622. },
  19623. set: function (value) {
  19624. if (this._useVertexColors === value) {
  19625. return;
  19626. }
  19627. this._useVertexColors = value;
  19628. this._markSubMeshesAsAttributesDirty();
  19629. },
  19630. enumerable: true,
  19631. configurable: true
  19632. });
  19633. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19634. /**
  19635. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19636. */
  19637. get: function () {
  19638. return this._computeBonesUsingShaders;
  19639. },
  19640. set: function (value) {
  19641. if (this._computeBonesUsingShaders === value) {
  19642. return;
  19643. }
  19644. this._computeBonesUsingShaders = value;
  19645. this._markSubMeshesAsAttributesDirty();
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19651. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19652. get: function () {
  19653. return this._numBoneInfluencers;
  19654. },
  19655. set: function (value) {
  19656. if (this._numBoneInfluencers === value) {
  19657. return;
  19658. }
  19659. this._numBoneInfluencers = value;
  19660. this._markSubMeshesAsAttributesDirty();
  19661. },
  19662. enumerable: true,
  19663. configurable: true
  19664. });
  19665. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19666. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19667. get: function () {
  19668. return this._applyFog;
  19669. },
  19670. set: function (value) {
  19671. if (this._applyFog === value) {
  19672. return;
  19673. }
  19674. this._applyFog = value;
  19675. this._markSubMeshesAsMiscDirty();
  19676. },
  19677. enumerable: true,
  19678. configurable: true
  19679. });
  19680. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19681. /**
  19682. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19683. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19684. */
  19685. get: function () {
  19686. return this._layerMask;
  19687. },
  19688. set: function (value) {
  19689. if (value === this._layerMask) {
  19690. return;
  19691. }
  19692. this._layerMask = value;
  19693. this._resyncLightSources();
  19694. },
  19695. enumerable: true,
  19696. configurable: true
  19697. });
  19698. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19699. /**
  19700. * Gets or sets a collision mask used to mask collisions (default is -1).
  19701. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19702. */
  19703. get: function () {
  19704. return this._collisionMask;
  19705. },
  19706. set: function (mask) {
  19707. this._collisionMask = !isNaN(mask) ? mask : -1;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19713. /**
  19714. * Gets or sets the current collision group mask (-1 by default).
  19715. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19716. */
  19717. get: function () {
  19718. return this._collisionGroup;
  19719. },
  19720. set: function (mask) {
  19721. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19727. /** @hidden */
  19728. get: function () {
  19729. return null;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19735. get: function () {
  19736. return this._skeleton;
  19737. },
  19738. /**
  19739. * Gets or sets a skeleton to apply skining transformations
  19740. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19741. */
  19742. set: function (value) {
  19743. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19744. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19745. }
  19746. if (value && value.needInitialSkinMatrix) {
  19747. value._registerMeshWithPoseMatrix(this);
  19748. }
  19749. this._skeleton = value;
  19750. if (!this._skeleton) {
  19751. this._bonesTransformMatrices = null;
  19752. }
  19753. this._markSubMeshesAsAttributesDirty();
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. /**
  19759. * Returns the string "AbstractMesh"
  19760. * @returns "AbstractMesh"
  19761. */
  19762. AbstractMesh.prototype.getClassName = function () {
  19763. return "AbstractMesh";
  19764. };
  19765. /**
  19766. * Gets a string representation of the current mesh
  19767. * @param fullDetails defines a boolean indicating if full details must be included
  19768. * @returns a string representation of the current mesh
  19769. */
  19770. AbstractMesh.prototype.toString = function (fullDetails) {
  19771. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19772. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19773. if (this._skeleton) {
  19774. ret += ", skeleton: " + this._skeleton.name;
  19775. }
  19776. if (fullDetails) {
  19777. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19778. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19779. }
  19780. return ret;
  19781. };
  19782. /** @hidden */
  19783. AbstractMesh.prototype._rebuild = function () {
  19784. if (this._occlusionQuery) {
  19785. this._occlusionQuery = null;
  19786. }
  19787. if (this._edgesRenderer) {
  19788. this._edgesRenderer._rebuild();
  19789. }
  19790. if (!this.subMeshes) {
  19791. return;
  19792. }
  19793. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19794. var subMesh = _a[_i];
  19795. subMesh._rebuild();
  19796. }
  19797. };
  19798. /** @hidden */
  19799. AbstractMesh.prototype._resyncLightSources = function () {
  19800. this._lightSources.length = 0;
  19801. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19802. var light = _a[_i];
  19803. if (!light.isEnabled()) {
  19804. continue;
  19805. }
  19806. if (light.canAffectMesh(this)) {
  19807. this._lightSources.push(light);
  19808. }
  19809. }
  19810. this._markSubMeshesAsLightDirty();
  19811. };
  19812. /** @hidden */
  19813. AbstractMesh.prototype._resyncLighSource = function (light) {
  19814. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19815. var index = this._lightSources.indexOf(light);
  19816. if (index === -1) {
  19817. if (!isIn) {
  19818. return;
  19819. }
  19820. this._lightSources.push(light);
  19821. }
  19822. else {
  19823. if (isIn) {
  19824. return;
  19825. }
  19826. this._lightSources.splice(index, 1);
  19827. }
  19828. this._markSubMeshesAsLightDirty();
  19829. };
  19830. /** @hidden */
  19831. AbstractMesh.prototype._unBindEffect = function () {
  19832. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19833. var subMesh = _a[_i];
  19834. subMesh.setEffect(null);
  19835. }
  19836. };
  19837. /** @hidden */
  19838. AbstractMesh.prototype._removeLightSource = function (light) {
  19839. var index = this._lightSources.indexOf(light);
  19840. if (index === -1) {
  19841. return;
  19842. }
  19843. this._lightSources.splice(index, 1);
  19844. this._markSubMeshesAsLightDirty();
  19845. };
  19846. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19847. if (!this.subMeshes) {
  19848. return;
  19849. }
  19850. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19851. var subMesh = _a[_i];
  19852. if (subMesh._materialDefines) {
  19853. func(subMesh._materialDefines);
  19854. }
  19855. }
  19856. };
  19857. /** @hidden */
  19858. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19859. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19860. };
  19861. /** @hidden */
  19862. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19863. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19864. };
  19865. /** @hidden */
  19866. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19867. if (!this.subMeshes) {
  19868. return;
  19869. }
  19870. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19871. var subMesh = _a[_i];
  19872. var material = subMesh.getMaterial();
  19873. if (material) {
  19874. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19875. }
  19876. }
  19877. };
  19878. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19879. /**
  19880. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19881. */
  19882. get: function () {
  19883. return this._scaling;
  19884. },
  19885. set: function (newScaling) {
  19886. this._scaling = newScaling;
  19887. if (this.physicsImpostor) {
  19888. this.physicsImpostor.forceUpdate();
  19889. }
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. // Methods
  19895. /**
  19896. * Disables the mesh edge rendering mode
  19897. * @returns the currentAbstractMesh
  19898. */
  19899. AbstractMesh.prototype.disableEdgesRendering = function () {
  19900. if (this._edgesRenderer) {
  19901. this._edgesRenderer.dispose();
  19902. this._edgesRenderer = null;
  19903. }
  19904. return this;
  19905. };
  19906. /**
  19907. * Enables the edge rendering mode on the mesh.
  19908. * This mode makes the mesh edges visible
  19909. * @param epsilon defines the maximal distance between two angles to detect a face
  19910. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19911. * @returns the currentAbstractMesh
  19912. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19913. */
  19914. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19915. if (epsilon === void 0) { epsilon = 0.95; }
  19916. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19917. this.disableEdgesRendering();
  19918. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19919. return this;
  19920. };
  19921. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  19922. /**
  19923. * Gets the edgesRenderer associated with the mesh
  19924. */
  19925. get: function () {
  19926. return this._edgesRenderer;
  19927. },
  19928. enumerable: true,
  19929. configurable: true
  19930. });
  19931. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19932. /**
  19933. * Returns true if the mesh is blocked. Implemented by child classes
  19934. */
  19935. get: function () {
  19936. return false;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. /**
  19942. * Returns the mesh itself by default. Implemented by child classes
  19943. * @param camera defines the camera to use to pick the right LOD level
  19944. * @returns the currentAbstractMesh
  19945. */
  19946. AbstractMesh.prototype.getLOD = function (camera) {
  19947. return this;
  19948. };
  19949. /**
  19950. * Returns 0 by default. Implemented by child classes
  19951. * @returns an integer
  19952. */
  19953. AbstractMesh.prototype.getTotalVertices = function () {
  19954. return 0;
  19955. };
  19956. /**
  19957. * Returns null by default. Implemented by child classes
  19958. * @returns null
  19959. */
  19960. AbstractMesh.prototype.getIndices = function () {
  19961. return null;
  19962. };
  19963. /**
  19964. * Returns the array of the requested vertex data kind. Implemented by child classes
  19965. * @param kind defines the vertex data kind to use
  19966. * @returns null
  19967. */
  19968. AbstractMesh.prototype.getVerticesData = function (kind) {
  19969. return null;
  19970. };
  19971. /**
  19972. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19973. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19974. * Note that a new underlying VertexBuffer object is created each call.
  19975. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19976. * @param kind defines vertex data kind:
  19977. * * BABYLON.VertexBuffer.PositionKind
  19978. * * BABYLON.VertexBuffer.UVKind
  19979. * * BABYLON.VertexBuffer.UV2Kind
  19980. * * BABYLON.VertexBuffer.UV3Kind
  19981. * * BABYLON.VertexBuffer.UV4Kind
  19982. * * BABYLON.VertexBuffer.UV5Kind
  19983. * * BABYLON.VertexBuffer.UV6Kind
  19984. * * BABYLON.VertexBuffer.ColorKind
  19985. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19986. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19987. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19988. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19989. * @param data defines the data source
  19990. * @param updatable defines if the data must be flagged as updatable (or static)
  19991. * @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
  19992. * @returns the current mesh
  19993. */
  19994. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19995. return this;
  19996. };
  19997. /**
  19998. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19999. * If the mesh has no geometry, it is simply returned as it is.
  20000. * @param kind defines vertex data kind:
  20001. * * BABYLON.VertexBuffer.PositionKind
  20002. * * BABYLON.VertexBuffer.UVKind
  20003. * * BABYLON.VertexBuffer.UV2Kind
  20004. * * BABYLON.VertexBuffer.UV3Kind
  20005. * * BABYLON.VertexBuffer.UV4Kind
  20006. * * BABYLON.VertexBuffer.UV5Kind
  20007. * * BABYLON.VertexBuffer.UV6Kind
  20008. * * BABYLON.VertexBuffer.ColorKind
  20009. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20010. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20011. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20012. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20013. * @param data defines the data source
  20014. * @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
  20015. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20016. * @returns the current mesh
  20017. */
  20018. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20019. return this;
  20020. };
  20021. /**
  20022. * Sets the mesh indices,
  20023. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20024. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20025. * @param totalVertices Defines the total number of vertices
  20026. * @returns the current mesh
  20027. */
  20028. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20029. return this;
  20030. };
  20031. /**
  20032. * Gets a boolean indicating if specific vertex data is present
  20033. * @param kind defines the vertex data kind to use
  20034. * @returns true is data kind is present
  20035. */
  20036. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20037. return false;
  20038. };
  20039. /**
  20040. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20041. * @returns a BoundingInfo
  20042. */
  20043. AbstractMesh.prototype.getBoundingInfo = function () {
  20044. if (this._masterMesh) {
  20045. return this._masterMesh.getBoundingInfo();
  20046. }
  20047. if (!this._boundingInfo) {
  20048. // this._boundingInfo is being created here
  20049. this._updateBoundingInfo();
  20050. }
  20051. // cannot be null.
  20052. return this._boundingInfo;
  20053. };
  20054. /**
  20055. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20056. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20057. * @returns the current mesh
  20058. */
  20059. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20060. if (includeDescendants === void 0) { includeDescendants = true; }
  20061. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20062. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20063. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20064. if (maxDimension === 0) {
  20065. return this;
  20066. }
  20067. var scale = 1 / maxDimension;
  20068. this.scaling.scaleInPlace(scale);
  20069. return this;
  20070. };
  20071. /**
  20072. * Overwrite the current bounding info
  20073. * @param boundingInfo defines the new bounding info
  20074. * @returns the current mesh
  20075. */
  20076. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20077. this._boundingInfo = boundingInfo;
  20078. return this;
  20079. };
  20080. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20081. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20082. get: function () {
  20083. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. /** @hidden */
  20089. AbstractMesh.prototype._preActivate = function () {
  20090. };
  20091. /** @hidden */
  20092. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20093. };
  20094. /** @hidden */
  20095. AbstractMesh.prototype._activate = function (renderId) {
  20096. this._renderId = renderId;
  20097. };
  20098. /**
  20099. * Gets the current world matrix
  20100. * @returns a Matrix
  20101. */
  20102. AbstractMesh.prototype.getWorldMatrix = function () {
  20103. if (this._masterMesh) {
  20104. return this._masterMesh.getWorldMatrix();
  20105. }
  20106. return _super.prototype.getWorldMatrix.call(this);
  20107. };
  20108. /** @hidden */
  20109. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20110. if (this._masterMesh) {
  20111. return this._masterMesh._getWorldMatrixDeterminant();
  20112. }
  20113. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20114. };
  20115. // ================================== Point of View Movement =================================
  20116. /**
  20117. * Perform relative position change from the point of view of behind the front of the mesh.
  20118. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20119. * Supports definition of mesh facing forward or backward
  20120. * @param amountRight defines the distance on the right axis
  20121. * @param amountUp defines the distance on the up axis
  20122. * @param amountForward defines the distance on the forward axis
  20123. * @returns the current mesh
  20124. */
  20125. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20126. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20127. return this;
  20128. };
  20129. /**
  20130. * Calculate relative position change from the point of view of behind the front of the mesh.
  20131. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20132. * Supports definition of mesh facing forward or backward
  20133. * @param amountRight defines the distance on the right axis
  20134. * @param amountUp defines the distance on the up axis
  20135. * @param amountForward defines the distance on the forward axis
  20136. * @returns the new displacement vector
  20137. */
  20138. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20139. var rotMatrix = new BABYLON.Matrix();
  20140. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20141. rotQuaternion.toRotationMatrix(rotMatrix);
  20142. var translationDelta = BABYLON.Vector3.Zero();
  20143. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20144. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20145. return translationDelta;
  20146. };
  20147. // ================================== Point of View Rotation =================================
  20148. /**
  20149. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20150. * Supports definition of mesh facing forward or backward
  20151. * @param flipBack defines the flip
  20152. * @param twirlClockwise defines the twirl
  20153. * @param tiltRight defines the tilt
  20154. * @returns the current mesh
  20155. */
  20156. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20157. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20158. return this;
  20159. };
  20160. /**
  20161. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20162. * Supports definition of mesh facing forward or backward.
  20163. * @param flipBack defines the flip
  20164. * @param twirlClockwise defines the twirl
  20165. * @param tiltRight defines the tilt
  20166. * @returns the new rotation vector
  20167. */
  20168. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20169. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20170. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20171. };
  20172. /**
  20173. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20174. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20175. * @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
  20176. * @returns the new bounding vectors
  20177. */
  20178. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20179. if (includeDescendants === void 0) { includeDescendants = true; }
  20180. if (predicate === void 0) { predicate = null; }
  20181. // Ensures that all world matrix will be recomputed.
  20182. this.getScene().incrementRenderId();
  20183. this.computeWorldMatrix(true);
  20184. var min;
  20185. var max;
  20186. var boundingInfo = this.getBoundingInfo();
  20187. if (!this.subMeshes) {
  20188. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20189. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20190. }
  20191. else {
  20192. min = boundingInfo.boundingBox.minimumWorld;
  20193. max = boundingInfo.boundingBox.maximumWorld;
  20194. }
  20195. if (includeDescendants) {
  20196. var descendants = this.getDescendants(false);
  20197. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20198. var descendant = descendants_1[_i];
  20199. var childMesh = descendant;
  20200. childMesh.computeWorldMatrix(true);
  20201. // Filters meshes based on custom predicate function.
  20202. if (predicate && !predicate(childMesh)) {
  20203. continue;
  20204. }
  20205. //make sure we have the needed params to get mix and max
  20206. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20207. continue;
  20208. }
  20209. var childBoundingInfo = childMesh.getBoundingInfo();
  20210. var boundingBox = childBoundingInfo.boundingBox;
  20211. var minBox = boundingBox.minimumWorld;
  20212. var maxBox = boundingBox.maximumWorld;
  20213. BABYLON.Tools.CheckExtends(minBox, min, max);
  20214. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20215. }
  20216. }
  20217. return {
  20218. min: min,
  20219. max: max
  20220. };
  20221. };
  20222. /** @hidden */
  20223. AbstractMesh.prototype._updateBoundingInfo = function () {
  20224. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20225. this._boundingInfo.update(this.worldMatrixFromCache);
  20226. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20227. return this;
  20228. };
  20229. /** @hidden */
  20230. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20231. if (!this.subMeshes) {
  20232. return this;
  20233. }
  20234. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20235. var subMesh = this.subMeshes[subIndex];
  20236. if (!subMesh.IsGlobal) {
  20237. subMesh.updateBoundingInfo(matrix);
  20238. }
  20239. }
  20240. return this;
  20241. };
  20242. /** @hidden */
  20243. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20244. // Bounding info
  20245. this._updateBoundingInfo();
  20246. };
  20247. /**
  20248. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20249. * A mesh is in the frustum if its bounding box intersects the frustum
  20250. * @param frustumPlanes defines the frustum to test
  20251. * @returns true if the mesh is in the frustum planes
  20252. */
  20253. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20254. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20255. };
  20256. /**
  20257. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20258. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20259. * @param frustumPlanes defines the frustum to test
  20260. * @returns true if the mesh is completely in the frustum planes
  20261. */
  20262. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20263. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20264. };
  20265. /**
  20266. * True if the mesh intersects another mesh or a SolidParticle object
  20267. * @param mesh defines a target mesh or SolidParticle to test
  20268. * @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)
  20269. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20270. * @returns true if there is an intersection
  20271. */
  20272. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20273. if (precise === void 0) { precise = false; }
  20274. if (!this._boundingInfo || !mesh._boundingInfo) {
  20275. return false;
  20276. }
  20277. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20278. return true;
  20279. }
  20280. if (includeDescendants) {
  20281. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20282. var child = _a[_i];
  20283. if (child.intersectsMesh(mesh, precise, true)) {
  20284. return true;
  20285. }
  20286. }
  20287. }
  20288. return false;
  20289. };
  20290. /**
  20291. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20292. * @param point defines the point to test
  20293. * @returns true if there is an intersection
  20294. */
  20295. AbstractMesh.prototype.intersectsPoint = function (point) {
  20296. if (!this._boundingInfo) {
  20297. return false;
  20298. }
  20299. return this._boundingInfo.intersectsPoint(point);
  20300. };
  20301. /**
  20302. * Gets the current physics impostor
  20303. * @see http://doc.babylonjs.com/features/physics_engine
  20304. * @returns a physics impostor or null
  20305. */
  20306. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20307. return this.physicsImpostor;
  20308. };
  20309. /**
  20310. * Gets the position of the current mesh in camera space
  20311. * @param camera defines the camera to use
  20312. * @returns a position
  20313. */
  20314. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20315. if (camera === void 0) { camera = null; }
  20316. if (!camera) {
  20317. camera = this.getScene().activeCamera;
  20318. }
  20319. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20320. };
  20321. /**
  20322. * Returns the distance from the mesh to the active camera
  20323. * @param camera defines the camera to use
  20324. * @returns the distance
  20325. */
  20326. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20327. if (camera === void 0) { camera = null; }
  20328. if (!camera) {
  20329. camera = this.getScene().activeCamera;
  20330. }
  20331. return this.absolutePosition.subtract(camera.position).length();
  20332. };
  20333. /**
  20334. * Apply a physic impulse to the mesh
  20335. * @param force defines the force to apply
  20336. * @param contactPoint defines where to apply the force
  20337. * @returns the current mesh
  20338. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20339. */
  20340. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20341. if (!this.physicsImpostor) {
  20342. return this;
  20343. }
  20344. this.physicsImpostor.applyImpulse(force, contactPoint);
  20345. return this;
  20346. };
  20347. /**
  20348. * Creates a physic joint between two meshes
  20349. * @param otherMesh defines the other mesh to use
  20350. * @param pivot1 defines the pivot to use on this mesh
  20351. * @param pivot2 defines the pivot to use on the other mesh
  20352. * @param options defines additional options (can be plugin dependent)
  20353. * @returns the current mesh
  20354. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20355. */
  20356. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20357. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20358. return this;
  20359. }
  20360. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20361. mainPivot: pivot1,
  20362. connectedPivot: pivot2,
  20363. nativeParams: options
  20364. });
  20365. return this;
  20366. };
  20367. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20368. // Collisions
  20369. /**
  20370. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20371. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20372. */
  20373. get: function () {
  20374. return this._checkCollisions;
  20375. },
  20376. set: function (collisionEnabled) {
  20377. this._checkCollisions = collisionEnabled;
  20378. if (this.getScene().workerCollisions) {
  20379. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20380. }
  20381. },
  20382. enumerable: true,
  20383. configurable: true
  20384. });
  20385. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20386. /**
  20387. * Gets Collider object used to compute collisions (not physics)
  20388. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20389. */
  20390. get: function () {
  20391. return this._collider;
  20392. },
  20393. enumerable: true,
  20394. configurable: true
  20395. });
  20396. /**
  20397. * Move the mesh using collision engine
  20398. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20399. * @param displacement defines the requested displacement vector
  20400. * @returns the current mesh
  20401. */
  20402. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20403. var globalPosition = this.getAbsolutePosition();
  20404. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20405. if (!this._collider) {
  20406. this._collider = new BABYLON.Collider();
  20407. }
  20408. this._collider._radius = this.ellipsoid;
  20409. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20410. return this;
  20411. };
  20412. // Submeshes octree
  20413. /**
  20414. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20415. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20416. * @param maxCapacity defines the maximum size of each block (64 by default)
  20417. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20418. * @returns the new octree
  20419. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20420. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20421. */
  20422. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20423. if (maxCapacity === void 0) { maxCapacity = 64; }
  20424. if (maxDepth === void 0) { maxDepth = 2; }
  20425. if (!this._submeshesOctree) {
  20426. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20427. }
  20428. this.computeWorldMatrix(true);
  20429. var boundingInfo = this.getBoundingInfo();
  20430. // Update octree
  20431. var bbox = boundingInfo.boundingBox;
  20432. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20433. return this._submeshesOctree;
  20434. };
  20435. // Collisions
  20436. /** @hidden */
  20437. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20438. this._generatePointsArray();
  20439. if (!this._positions) {
  20440. return this;
  20441. }
  20442. // Transformation
  20443. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20444. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20445. subMesh._lastColliderWorldVertices = [];
  20446. subMesh._trianglePlanes = [];
  20447. var start = subMesh.verticesStart;
  20448. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20449. for (var i = start; i < end; i++) {
  20450. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20451. }
  20452. }
  20453. // Collide
  20454. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20455. if (collider.collisionFound) {
  20456. collider.collidedMesh = this;
  20457. }
  20458. return this;
  20459. };
  20460. /** @hidden */
  20461. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20462. var subMeshes;
  20463. var len;
  20464. // Octrees
  20465. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20466. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20467. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20468. len = intersections.length;
  20469. subMeshes = intersections.data;
  20470. }
  20471. else {
  20472. subMeshes = this.subMeshes;
  20473. len = subMeshes.length;
  20474. }
  20475. for (var index = 0; index < len; index++) {
  20476. var subMesh = subMeshes[index];
  20477. // Bounding test
  20478. if (len > 1 && !subMesh._checkCollision(collider))
  20479. continue;
  20480. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20481. }
  20482. return this;
  20483. };
  20484. /** @hidden */
  20485. AbstractMesh.prototype._checkCollision = function (collider) {
  20486. // Bounding box test
  20487. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20488. return this;
  20489. // Transformation matrix
  20490. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20491. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20492. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20493. return this;
  20494. };
  20495. // Picking
  20496. /** @hidden */
  20497. AbstractMesh.prototype._generatePointsArray = function () {
  20498. return false;
  20499. };
  20500. /**
  20501. * Checks if the passed Ray intersects with the mesh
  20502. * @param ray defines the ray to use
  20503. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20504. * @returns the picking info
  20505. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20506. */
  20507. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20508. var pickingInfo = new BABYLON.PickingInfo();
  20509. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20510. return pickingInfo;
  20511. }
  20512. if (!this._generatePointsArray()) {
  20513. return pickingInfo;
  20514. }
  20515. var intersectInfo = null;
  20516. // Octrees
  20517. var subMeshes;
  20518. var len;
  20519. if (this._submeshesOctree && this.useOctreeForPicking) {
  20520. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20521. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20522. len = intersections.length;
  20523. subMeshes = intersections.data;
  20524. }
  20525. else {
  20526. subMeshes = this.subMeshes;
  20527. len = subMeshes.length;
  20528. }
  20529. for (var index = 0; index < len; index++) {
  20530. var subMesh = subMeshes[index];
  20531. // Bounding test
  20532. if (len > 1 && !subMesh.canIntersects(ray))
  20533. continue;
  20534. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20535. if (currentIntersectInfo) {
  20536. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20537. intersectInfo = currentIntersectInfo;
  20538. intersectInfo.subMeshId = index;
  20539. if (fastCheck) {
  20540. break;
  20541. }
  20542. }
  20543. }
  20544. }
  20545. if (intersectInfo) {
  20546. // Get picked point
  20547. var world = this.getWorldMatrix();
  20548. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20549. var direction = ray.direction.clone();
  20550. direction = direction.scale(intersectInfo.distance);
  20551. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20552. var pickedPoint = worldOrigin.add(worldDirection);
  20553. // Return result
  20554. pickingInfo.hit = true;
  20555. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20556. pickingInfo.pickedPoint = pickedPoint;
  20557. pickingInfo.pickedMesh = this;
  20558. pickingInfo.bu = intersectInfo.bu || 0;
  20559. pickingInfo.bv = intersectInfo.bv || 0;
  20560. pickingInfo.faceId = intersectInfo.faceId;
  20561. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20562. return pickingInfo;
  20563. }
  20564. return pickingInfo;
  20565. };
  20566. /**
  20567. * Clones the current mesh
  20568. * @param name defines the mesh name
  20569. * @param newParent defines the new mesh parent
  20570. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20571. * @returns the new mesh
  20572. */
  20573. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20574. return null;
  20575. };
  20576. /**
  20577. * Disposes all the submeshes of the current meshnp
  20578. * @returns the current mesh
  20579. */
  20580. AbstractMesh.prototype.releaseSubMeshes = function () {
  20581. if (this.subMeshes) {
  20582. while (this.subMeshes.length) {
  20583. this.subMeshes[0].dispose();
  20584. }
  20585. }
  20586. else {
  20587. this.subMeshes = new Array();
  20588. }
  20589. return this;
  20590. };
  20591. /**
  20592. * Releases resources associated with this abstract mesh.
  20593. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20594. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20595. */
  20596. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20597. var _this = this;
  20598. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20599. var index;
  20600. // Smart Array Retainers.
  20601. this.getScene().freeActiveMeshes();
  20602. this.getScene().freeRenderingGroups();
  20603. // Action manager
  20604. if (this.actionManager !== undefined && this.actionManager !== null) {
  20605. this.actionManager.dispose();
  20606. this.actionManager = null;
  20607. }
  20608. // Skeleton
  20609. this._skeleton = null;
  20610. // Physics
  20611. if (this.physicsImpostor) {
  20612. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20613. }
  20614. // Intersections in progress
  20615. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20616. var other = this._intersectionsInProgress[index];
  20617. var pos = other._intersectionsInProgress.indexOf(this);
  20618. other._intersectionsInProgress.splice(pos, 1);
  20619. }
  20620. this._intersectionsInProgress = [];
  20621. // Lights
  20622. var lights = this.getScene().lights;
  20623. lights.forEach(function (light) {
  20624. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20625. if (meshIndex !== -1) {
  20626. light.includedOnlyMeshes.splice(meshIndex, 1);
  20627. }
  20628. meshIndex = light.excludedMeshes.indexOf(_this);
  20629. if (meshIndex !== -1) {
  20630. light.excludedMeshes.splice(meshIndex, 1);
  20631. }
  20632. // Shadow generators
  20633. var generator = light.getShadowGenerator();
  20634. if (generator) {
  20635. var shadowMap = generator.getShadowMap();
  20636. if (shadowMap && shadowMap.renderList) {
  20637. meshIndex = shadowMap.renderList.indexOf(_this);
  20638. if (meshIndex !== -1) {
  20639. shadowMap.renderList.splice(meshIndex, 1);
  20640. }
  20641. }
  20642. }
  20643. });
  20644. // Edges
  20645. if (this._edgesRenderer) {
  20646. this._edgesRenderer.dispose();
  20647. this._edgesRenderer = null;
  20648. }
  20649. // SubMeshes
  20650. if (this.getClassName() !== "InstancedMesh") {
  20651. this.releaseSubMeshes();
  20652. }
  20653. // Octree
  20654. var sceneOctree = this.getScene().selectionOctree;
  20655. if (sceneOctree !== undefined && sceneOctree !== null) {
  20656. var index = sceneOctree.dynamicContent.indexOf(this);
  20657. if (index !== -1) {
  20658. sceneOctree.dynamicContent.splice(index, 1);
  20659. }
  20660. }
  20661. // Query
  20662. var engine = this.getScene().getEngine();
  20663. if (this._occlusionQuery) {
  20664. this._isOcclusionQueryInProgress = false;
  20665. engine.deleteQuery(this._occlusionQuery);
  20666. this._occlusionQuery = null;
  20667. }
  20668. // Engine
  20669. engine.wipeCaches();
  20670. // Remove from scene
  20671. this.getScene().removeMesh(this);
  20672. if (disposeMaterialAndTextures) {
  20673. if (this.material) {
  20674. this.material.dispose(false, true);
  20675. }
  20676. }
  20677. if (!doNotRecurse) {
  20678. // Particles
  20679. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20680. if (this.getScene().particleSystems[index].emitter === this) {
  20681. this.getScene().particleSystems[index].dispose();
  20682. index--;
  20683. }
  20684. }
  20685. }
  20686. // facet data
  20687. if (this._facetDataEnabled) {
  20688. this.disableFacetData();
  20689. }
  20690. this.onAfterWorldMatrixUpdateObservable.clear();
  20691. this.onCollideObservable.clear();
  20692. this.onCollisionPositionChangeObservable.clear();
  20693. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20694. };
  20695. /**
  20696. * Adds the passed mesh as a child to the current mesh
  20697. * @param mesh defines the child mesh
  20698. * @returns the current mesh
  20699. */
  20700. AbstractMesh.prototype.addChild = function (mesh) {
  20701. mesh.setParent(this);
  20702. return this;
  20703. };
  20704. /**
  20705. * Removes the passed mesh from the current mesh children list
  20706. * @param mesh defines the child mesh
  20707. * @returns the current mesh
  20708. */
  20709. AbstractMesh.prototype.removeChild = function (mesh) {
  20710. mesh.setParent(null);
  20711. return this;
  20712. };
  20713. // Facet data
  20714. /** @hidden */
  20715. AbstractMesh.prototype._initFacetData = function () {
  20716. if (!this._facetNormals) {
  20717. this._facetNormals = new Array();
  20718. }
  20719. if (!this._facetPositions) {
  20720. this._facetPositions = new Array();
  20721. }
  20722. if (!this._facetPartitioning) {
  20723. this._facetPartitioning = new Array();
  20724. }
  20725. this._facetNb = (this.getIndices().length / 3) | 0;
  20726. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20727. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20728. for (var f = 0; f < this._facetNb; f++) {
  20729. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20730. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20731. }
  20732. this._facetDataEnabled = true;
  20733. return this;
  20734. };
  20735. /**
  20736. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20737. * This method can be called within the render loop.
  20738. * 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
  20739. * @returns the current mesh
  20740. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20741. */
  20742. AbstractMesh.prototype.updateFacetData = function () {
  20743. if (!this._facetDataEnabled) {
  20744. this._initFacetData();
  20745. }
  20746. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20747. var indices = this.getIndices();
  20748. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20749. var bInfo = this.getBoundingInfo();
  20750. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20751. // init arrays, matrix and sort function on first call
  20752. this._facetDepthSortEnabled = true;
  20753. if (indices instanceof Uint16Array) {
  20754. this._depthSortedIndices = new Uint16Array(indices);
  20755. }
  20756. else if (indices instanceof Uint32Array) {
  20757. this._depthSortedIndices = new Uint32Array(indices);
  20758. }
  20759. else {
  20760. var needs32bits = false;
  20761. for (var i = 0; i < indices.length; i++) {
  20762. if (indices[i] > 65535) {
  20763. needs32bits = true;
  20764. break;
  20765. }
  20766. }
  20767. if (needs32bits) {
  20768. this._depthSortedIndices = new Uint32Array(indices);
  20769. }
  20770. else {
  20771. this._depthSortedIndices = new Uint16Array(indices);
  20772. }
  20773. }
  20774. this._facetDepthSortFunction = function (f1, f2) {
  20775. return (f2.sqDistance - f1.sqDistance);
  20776. };
  20777. if (!this._facetDepthSortFrom) {
  20778. var camera = this.getScene().activeCamera;
  20779. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20780. }
  20781. this._depthSortedFacets = [];
  20782. for (var f = 0; f < this._facetNb; f++) {
  20783. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20784. this._depthSortedFacets.push(depthSortedFacet);
  20785. }
  20786. this._invertedMatrix = BABYLON.Matrix.Identity();
  20787. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20788. }
  20789. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20790. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20791. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20792. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20793. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20794. this._subDiv.max = this._partitioningSubdivisions;
  20795. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20796. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20797. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20798. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20799. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20800. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20801. // set the parameters for ComputeNormals()
  20802. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20803. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20804. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20805. this._facetParameters.bInfo = bInfo;
  20806. this._facetParameters.bbSize = this._bbSize;
  20807. this._facetParameters.subDiv = this._subDiv;
  20808. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20809. this._facetParameters.depthSort = this._facetDepthSort;
  20810. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20811. this.computeWorldMatrix(true);
  20812. this._worldMatrix.invertToRef(this._invertedMatrix);
  20813. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20814. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20815. }
  20816. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20817. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20818. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20819. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20820. var l = (this._depthSortedIndices.length / 3) | 0;
  20821. for (var f = 0; f < l; f++) {
  20822. var sind = this._depthSortedFacets[f].ind;
  20823. this._depthSortedIndices[f * 3] = indices[sind];
  20824. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20825. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20826. }
  20827. this.updateIndices(this._depthSortedIndices);
  20828. }
  20829. return this;
  20830. };
  20831. /**
  20832. * Returns the facetLocalNormals array.
  20833. * The normals are expressed in the mesh local spac
  20834. * @returns an array of Vector3
  20835. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20836. */
  20837. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20838. if (!this._facetNormals) {
  20839. this.updateFacetData();
  20840. }
  20841. return this._facetNormals;
  20842. };
  20843. /**
  20844. * Returns the facetLocalPositions array.
  20845. * The facet positions are expressed in the mesh local space
  20846. * @returns an array of Vector3
  20847. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20848. */
  20849. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20850. if (!this._facetPositions) {
  20851. this.updateFacetData();
  20852. }
  20853. return this._facetPositions;
  20854. };
  20855. /**
  20856. * Returns the facetLocalPartioning array
  20857. * @returns an array of array of numbers
  20858. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20859. */
  20860. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20861. if (!this._facetPartitioning) {
  20862. this.updateFacetData();
  20863. }
  20864. return this._facetPartitioning;
  20865. };
  20866. /**
  20867. * Returns the i-th facet position in the world system.
  20868. * This method allocates a new Vector3 per call
  20869. * @param i defines the facet index
  20870. * @returns a new Vector3
  20871. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20872. */
  20873. AbstractMesh.prototype.getFacetPosition = function (i) {
  20874. var pos = BABYLON.Vector3.Zero();
  20875. this.getFacetPositionToRef(i, pos);
  20876. return pos;
  20877. };
  20878. /**
  20879. * Sets the reference Vector3 with the i-th facet position in the world system
  20880. * @param i defines the facet index
  20881. * @param ref defines the target vector
  20882. * @returns the current mesh
  20883. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20884. */
  20885. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20886. var localPos = (this.getFacetLocalPositions())[i];
  20887. var world = this.getWorldMatrix();
  20888. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20889. return this;
  20890. };
  20891. /**
  20892. * Returns the i-th facet normal in the world system.
  20893. * This method allocates a new Vector3 per call
  20894. * @param i defines the facet index
  20895. * @returns a new Vector3
  20896. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20897. */
  20898. AbstractMesh.prototype.getFacetNormal = function (i) {
  20899. var norm = BABYLON.Vector3.Zero();
  20900. this.getFacetNormalToRef(i, norm);
  20901. return norm;
  20902. };
  20903. /**
  20904. * Sets the reference Vector3 with the i-th facet normal in the world system
  20905. * @param i defines the facet index
  20906. * @param ref defines the target vector
  20907. * @returns the current mesh
  20908. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20909. */
  20910. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20911. var localNorm = (this.getFacetLocalNormals())[i];
  20912. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20913. return this;
  20914. };
  20915. /**
  20916. * 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)
  20917. * @param x defines x coordinate
  20918. * @param y defines y coordinate
  20919. * @param z defines z coordinate
  20920. * @returns the array of facet indexes
  20921. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20922. */
  20923. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20924. var bInfo = this.getBoundingInfo();
  20925. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20926. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20927. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20928. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20929. return null;
  20930. }
  20931. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20932. };
  20933. /**
  20934. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20935. * @param projected sets as the (x,y,z) world projection on the facet
  20936. * @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
  20937. * @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
  20938. * @param x defines x coordinate
  20939. * @param y defines y coordinate
  20940. * @param z defines z coordinate
  20941. * @returns the face index if found (or null instead)
  20942. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20943. */
  20944. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20945. if (checkFace === void 0) { checkFace = false; }
  20946. if (facing === void 0) { facing = true; }
  20947. var world = this.getWorldMatrix();
  20948. var invMat = BABYLON.Tmp.Matrix[5];
  20949. world.invertToRef(invMat);
  20950. var invVect = BABYLON.Tmp.Vector3[8];
  20951. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20952. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20953. if (projected) {
  20954. // tranform the local computed projected vector to world coordinates
  20955. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20956. }
  20957. return closest;
  20958. };
  20959. /**
  20960. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20961. * @param projected sets as the (x,y,z) local projection on the facet
  20962. * @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
  20963. * @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
  20964. * @param x defines x coordinate
  20965. * @param y defines y coordinate
  20966. * @param z defines z coordinate
  20967. * @returns the face index if found (or null instead)
  20968. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20969. */
  20970. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20971. if (checkFace === void 0) { checkFace = false; }
  20972. if (facing === void 0) { facing = true; }
  20973. var closest = null;
  20974. var tmpx = 0.0;
  20975. var tmpy = 0.0;
  20976. var tmpz = 0.0;
  20977. var d = 0.0; // tmp dot facet normal * facet position
  20978. var t0 = 0.0;
  20979. var projx = 0.0;
  20980. var projy = 0.0;
  20981. var projz = 0.0;
  20982. // Get all the facets in the same partitioning block than (x, y, z)
  20983. var facetPositions = this.getFacetLocalPositions();
  20984. var facetNormals = this.getFacetLocalNormals();
  20985. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20986. if (!facetsInBlock) {
  20987. return null;
  20988. }
  20989. // Get the closest facet to (x, y, z)
  20990. var shortest = Number.MAX_VALUE; // init distance vars
  20991. var tmpDistance = shortest;
  20992. var fib; // current facet in the block
  20993. var norm; // current facet normal
  20994. var p0; // current facet barycenter position
  20995. // loop on all the facets in the current partitioning block
  20996. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20997. fib = facetsInBlock[idx];
  20998. norm = facetNormals[fib];
  20999. p0 = facetPositions[fib];
  21000. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21001. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21002. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21003. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21004. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21005. projx = x + norm.x * t0;
  21006. projy = y + norm.y * t0;
  21007. projz = z + norm.z * t0;
  21008. tmpx = projx - x;
  21009. tmpy = projy - y;
  21010. tmpz = projz - z;
  21011. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21012. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21013. shortest = tmpDistance;
  21014. closest = fib;
  21015. if (projected) {
  21016. projected.x = projx;
  21017. projected.y = projy;
  21018. projected.z = projz;
  21019. }
  21020. }
  21021. }
  21022. }
  21023. return closest;
  21024. };
  21025. /**
  21026. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21027. * @returns the parameters
  21028. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21029. */
  21030. AbstractMesh.prototype.getFacetDataParameters = function () {
  21031. return this._facetParameters;
  21032. };
  21033. /**
  21034. * Disables the feature FacetData and frees the related memory
  21035. * @returns the current mesh
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.disableFacetData = function () {
  21039. if (this._facetDataEnabled) {
  21040. this._facetDataEnabled = false;
  21041. this._facetPositions = new Array();
  21042. this._facetNormals = new Array();
  21043. this._facetPartitioning = new Array();
  21044. this._facetParameters = null;
  21045. this._depthSortedIndices = new Uint32Array(0);
  21046. }
  21047. return this;
  21048. };
  21049. /**
  21050. * Updates the AbstractMesh indices array
  21051. * @param indices defines the data source
  21052. * @returns the current mesh
  21053. */
  21054. AbstractMesh.prototype.updateIndices = function (indices) {
  21055. return this;
  21056. };
  21057. /**
  21058. * Creates new normals data for the mesh
  21059. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21060. * @returns the current mesh
  21061. */
  21062. AbstractMesh.prototype.createNormals = function (updatable) {
  21063. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21064. var indices = this.getIndices();
  21065. var normals;
  21066. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21067. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21068. }
  21069. else {
  21070. normals = [];
  21071. }
  21072. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21073. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21074. return this;
  21075. };
  21076. /**
  21077. * Align the mesh with a normal
  21078. * @param normal defines the normal to use
  21079. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21080. * @returns the current mesh
  21081. */
  21082. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21083. if (!upDirection) {
  21084. upDirection = BABYLON.Axis.Y;
  21085. }
  21086. var axisX = BABYLON.Tmp.Vector3[0];
  21087. var axisZ = BABYLON.Tmp.Vector3[1];
  21088. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21089. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21090. if (this.rotationQuaternion) {
  21091. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21092. }
  21093. else {
  21094. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21095. }
  21096. return this;
  21097. };
  21098. /** @hidden */
  21099. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21100. this._isOccluded = false;
  21101. };
  21102. /** No occlusion */
  21103. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21104. /** Occlusion set to optimisitic */
  21105. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21106. /** Occlusion set to strict */
  21107. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21108. /** Use an accurante occlusion algorithm */
  21109. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21110. /** Use a conservative occlusion algorithm */
  21111. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21112. return AbstractMesh;
  21113. }(BABYLON.TransformNode));
  21114. BABYLON.AbstractMesh = AbstractMesh;
  21115. })(BABYLON || (BABYLON = {}));
  21116. //# sourceMappingURL=babylon.abstractMesh.js.map
  21117. var BABYLON;
  21118. (function (BABYLON) {
  21119. /**
  21120. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21121. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21122. * 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.
  21123. */
  21124. var Light = /** @class */ (function (_super) {
  21125. __extends(Light, _super);
  21126. /**
  21127. * Creates a Light object in the scene.
  21128. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21129. * @param name The firendly name of the light
  21130. * @param scene The scene the light belongs too
  21131. */
  21132. function Light(name, scene) {
  21133. var _this = _super.call(this, name, scene) || this;
  21134. /**
  21135. * Diffuse gives the basic color to an object.
  21136. */
  21137. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21138. /**
  21139. * Specular produces a highlight color on an object.
  21140. * Note: This is note affecting PBR materials.
  21141. */
  21142. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21143. /**
  21144. * Strength of the light.
  21145. * Note: By default it is define in the framework own unit.
  21146. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21147. */
  21148. _this.intensity = 1.0;
  21149. /**
  21150. * Defines how far from the source the light is impacting in scene units.
  21151. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21152. */
  21153. _this.range = Number.MAX_VALUE;
  21154. /**
  21155. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21156. * of light.
  21157. */
  21158. _this._photometricScale = 1.0;
  21159. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21160. _this._radius = 0.00001;
  21161. /**
  21162. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21163. * exceeding the number allowed of the materials.
  21164. */
  21165. _this.renderPriority = 0;
  21166. _this._shadowEnabled = true;
  21167. _this._excludeWithLayerMask = 0;
  21168. _this._includeOnlyWithLayerMask = 0;
  21169. _this._lightmapMode = 0;
  21170. /**
  21171. * @hidden Internal use only.
  21172. */
  21173. _this._excludedMeshesIds = new Array();
  21174. /**
  21175. * @hidden Internal use only.
  21176. */
  21177. _this._includedOnlyMeshesIds = new Array();
  21178. _this.getScene().addLight(_this);
  21179. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21180. _this._buildUniformLayout();
  21181. _this.includedOnlyMeshes = new Array();
  21182. _this.excludedMeshes = new Array();
  21183. _this._resyncMeshes();
  21184. return _this;
  21185. }
  21186. Object.defineProperty(Light.prototype, "intensityMode", {
  21187. /**
  21188. * Gets the photometric scale used to interpret the intensity.
  21189. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21190. */
  21191. get: function () {
  21192. return this._intensityMode;
  21193. },
  21194. /**
  21195. * Sets the photometric scale used to interpret the intensity.
  21196. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21197. */
  21198. set: function (value) {
  21199. this._intensityMode = value;
  21200. this._computePhotometricScale();
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. ;
  21206. ;
  21207. Object.defineProperty(Light.prototype, "radius", {
  21208. /**
  21209. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21210. */
  21211. get: function () {
  21212. return this._radius;
  21213. },
  21214. /**
  21215. * sets the light radius used by PBR Materials to simulate soft area lights.
  21216. */
  21217. set: function (value) {
  21218. this._radius = value;
  21219. this._computePhotometricScale();
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. ;
  21225. ;
  21226. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21227. /**
  21228. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21229. * the current shadow generator.
  21230. */
  21231. get: function () {
  21232. return this._shadowEnabled;
  21233. },
  21234. /**
  21235. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21236. * the current shadow generator.
  21237. */
  21238. set: function (value) {
  21239. if (this._shadowEnabled === value) {
  21240. return;
  21241. }
  21242. this._shadowEnabled = value;
  21243. this._markMeshesAsLightDirty();
  21244. },
  21245. enumerable: true,
  21246. configurable: true
  21247. });
  21248. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21249. /**
  21250. * Gets the only meshes impacted by this light.
  21251. */
  21252. get: function () {
  21253. return this._includedOnlyMeshes;
  21254. },
  21255. /**
  21256. * Sets the only meshes impacted by this light.
  21257. */
  21258. set: function (value) {
  21259. this._includedOnlyMeshes = value;
  21260. this._hookArrayForIncludedOnly(value);
  21261. },
  21262. enumerable: true,
  21263. configurable: true
  21264. });
  21265. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21266. /**
  21267. * Gets the meshes not impacted by this light.
  21268. */
  21269. get: function () {
  21270. return this._excludedMeshes;
  21271. },
  21272. /**
  21273. * Sets the meshes not impacted by this light.
  21274. */
  21275. set: function (value) {
  21276. this._excludedMeshes = value;
  21277. this._hookArrayForExcluded(value);
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21283. /**
  21284. * Gets the layer id use to find what meshes are not impacted by the light.
  21285. * Inactive if 0
  21286. */
  21287. get: function () {
  21288. return this._excludeWithLayerMask;
  21289. },
  21290. /**
  21291. * Sets the layer id use to find what meshes are not impacted by the light.
  21292. * Inactive if 0
  21293. */
  21294. set: function (value) {
  21295. this._excludeWithLayerMask = value;
  21296. this._resyncMeshes();
  21297. },
  21298. enumerable: true,
  21299. configurable: true
  21300. });
  21301. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21302. /**
  21303. * Gets the layer id use to find what meshes are impacted by the light.
  21304. * Inactive if 0
  21305. */
  21306. get: function () {
  21307. return this._includeOnlyWithLayerMask;
  21308. },
  21309. /**
  21310. * Sets the layer id use to find what meshes are impacted by the light.
  21311. * Inactive if 0
  21312. */
  21313. set: function (value) {
  21314. this._includeOnlyWithLayerMask = value;
  21315. this._resyncMeshes();
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(Light.prototype, "lightmapMode", {
  21321. /**
  21322. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21323. */
  21324. get: function () {
  21325. return this._lightmapMode;
  21326. },
  21327. /**
  21328. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21329. */
  21330. set: function (value) {
  21331. if (this._lightmapMode === value) {
  21332. return;
  21333. }
  21334. this._lightmapMode = value;
  21335. this._markMeshesAsLightDirty();
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. /**
  21341. * Returns the string "Light".
  21342. * @returns the class name
  21343. */
  21344. Light.prototype.getClassName = function () {
  21345. return "Light";
  21346. };
  21347. /**
  21348. * Converts the light information to a readable string for debug purpose.
  21349. * @param fullDetails Supports for multiple levels of logging within scene loading
  21350. * @returns the human readable light info
  21351. */
  21352. Light.prototype.toString = function (fullDetails) {
  21353. var ret = "Name: " + this.name;
  21354. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21355. if (this.animations) {
  21356. for (var i = 0; i < this.animations.length; i++) {
  21357. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21358. }
  21359. }
  21360. if (fullDetails) {
  21361. }
  21362. return ret;
  21363. };
  21364. /**
  21365. * Set the enabled state of this node.
  21366. * @param value - the new enabled state
  21367. */
  21368. Light.prototype.setEnabled = function (value) {
  21369. _super.prototype.setEnabled.call(this, value);
  21370. this._resyncMeshes();
  21371. };
  21372. /**
  21373. * Returns the Light associated shadow generator if any.
  21374. * @return the associated shadow generator.
  21375. */
  21376. Light.prototype.getShadowGenerator = function () {
  21377. return this._shadowGenerator;
  21378. };
  21379. /**
  21380. * Returns a Vector3, the absolute light position in the World.
  21381. * @returns the world space position of the light
  21382. */
  21383. Light.prototype.getAbsolutePosition = function () {
  21384. return BABYLON.Vector3.Zero();
  21385. };
  21386. /**
  21387. * Specifies if the light will affect the passed mesh.
  21388. * @param mesh The mesh to test against the light
  21389. * @return true the mesh is affected otherwise, false.
  21390. */
  21391. Light.prototype.canAffectMesh = function (mesh) {
  21392. if (!mesh) {
  21393. return true;
  21394. }
  21395. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21396. return false;
  21397. }
  21398. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21399. return false;
  21400. }
  21401. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21402. return false;
  21403. }
  21404. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21405. return false;
  21406. }
  21407. return true;
  21408. };
  21409. /**
  21410. * Computes and Returns the light World matrix.
  21411. * @returns the world matrix
  21412. */
  21413. Light.prototype.getWorldMatrix = function () {
  21414. this._currentRenderId = this.getScene().getRenderId();
  21415. this._childRenderId = this._currentRenderId;
  21416. var worldMatrix = this._getWorldMatrix();
  21417. if (this.parent && this.parent.getWorldMatrix) {
  21418. if (!this._parentedWorldMatrix) {
  21419. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21420. }
  21421. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21422. this._markSyncedWithParent();
  21423. return this._parentedWorldMatrix;
  21424. }
  21425. return worldMatrix;
  21426. };
  21427. /**
  21428. * Sort function to order lights for rendering.
  21429. * @param a First Light object to compare to second.
  21430. * @param b Second Light object to compare first.
  21431. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21432. */
  21433. Light.CompareLightsPriority = function (a, b) {
  21434. //shadow-casting lights have priority over non-shadow-casting lights
  21435. //the renderPrioirty is a secondary sort criterion
  21436. if (a.shadowEnabled !== b.shadowEnabled) {
  21437. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21438. }
  21439. return b.renderPriority - a.renderPriority;
  21440. };
  21441. /**
  21442. * Releases resources associated with this node.
  21443. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21444. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21445. */
  21446. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21447. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21448. if (this._shadowGenerator) {
  21449. this._shadowGenerator.dispose();
  21450. this._shadowGenerator = null;
  21451. }
  21452. // Animations
  21453. this.getScene().stopAnimation(this);
  21454. // Remove from meshes
  21455. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21456. var mesh = _a[_i];
  21457. mesh._removeLightSource(this);
  21458. }
  21459. this._uniformBuffer.dispose();
  21460. // Remove from scene
  21461. this.getScene().removeLight(this);
  21462. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21463. };
  21464. /**
  21465. * Returns the light type ID (integer).
  21466. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21467. */
  21468. Light.prototype.getTypeID = function () {
  21469. return 0;
  21470. };
  21471. /**
  21472. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21473. * @returns the scaled intensity in intensity mode unit
  21474. */
  21475. Light.prototype.getScaledIntensity = function () {
  21476. return this._photometricScale * this.intensity;
  21477. };
  21478. /**
  21479. * Returns a new Light object, named "name", from the current one.
  21480. * @param name The name of the cloned light
  21481. * @returns the new created light
  21482. */
  21483. Light.prototype.clone = function (name) {
  21484. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21485. if (!constructor) {
  21486. return null;
  21487. }
  21488. return BABYLON.SerializationHelper.Clone(constructor, this);
  21489. };
  21490. /**
  21491. * Serializes the current light into a Serialization object.
  21492. * @returns the serialized object.
  21493. */
  21494. Light.prototype.serialize = function () {
  21495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21496. // Type
  21497. serializationObject.type = this.getTypeID();
  21498. // Parent
  21499. if (this.parent) {
  21500. serializationObject.parentId = this.parent.id;
  21501. }
  21502. // Inclusion / exclusions
  21503. if (this.excludedMeshes.length > 0) {
  21504. serializationObject.excludedMeshesIds = [];
  21505. this.excludedMeshes.forEach(function (mesh) {
  21506. serializationObject.excludedMeshesIds.push(mesh.id);
  21507. });
  21508. }
  21509. if (this.includedOnlyMeshes.length > 0) {
  21510. serializationObject.includedOnlyMeshesIds = [];
  21511. this.includedOnlyMeshes.forEach(function (mesh) {
  21512. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21513. });
  21514. }
  21515. // Animations
  21516. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21517. serializationObject.ranges = this.serializeAnimationRanges();
  21518. return serializationObject;
  21519. };
  21520. /**
  21521. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21522. * This new light is named "name" and added to the passed scene.
  21523. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21524. * @param name The friendly name of the light
  21525. * @param scene The scene the new light will belong to
  21526. * @returns the constructor function
  21527. */
  21528. Light.GetConstructorFromName = function (type, name, scene) {
  21529. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21530. if (constructorFunc) {
  21531. return constructorFunc;
  21532. }
  21533. // Default to no light for none present once.
  21534. return null;
  21535. };
  21536. /**
  21537. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21538. * @param parsedLight The JSON representation of the light
  21539. * @param scene The scene to create the parsed light in
  21540. * @returns the created light after parsing
  21541. */
  21542. Light.Parse = function (parsedLight, scene) {
  21543. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21544. if (!constructor) {
  21545. return null;
  21546. }
  21547. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21548. // Inclusion / exclusions
  21549. if (parsedLight.excludedMeshesIds) {
  21550. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21551. }
  21552. if (parsedLight.includedOnlyMeshesIds) {
  21553. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21554. }
  21555. // Parent
  21556. if (parsedLight.parentId) {
  21557. light._waitingParentId = parsedLight.parentId;
  21558. }
  21559. // Animations
  21560. if (parsedLight.animations) {
  21561. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21562. var parsedAnimation = parsedLight.animations[animationIndex];
  21563. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21564. }
  21565. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21566. }
  21567. if (parsedLight.autoAnimate) {
  21568. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21569. }
  21570. return light;
  21571. };
  21572. Light.prototype._hookArrayForExcluded = function (array) {
  21573. var _this = this;
  21574. var oldPush = array.push;
  21575. array.push = function () {
  21576. var items = [];
  21577. for (var _i = 0; _i < arguments.length; _i++) {
  21578. items[_i] = arguments[_i];
  21579. }
  21580. var result = oldPush.apply(array, items);
  21581. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21582. var item = items_1[_a];
  21583. item._resyncLighSource(_this);
  21584. }
  21585. return result;
  21586. };
  21587. var oldSplice = array.splice;
  21588. array.splice = function (index, deleteCount) {
  21589. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21590. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21591. var item = deleted_1[_i];
  21592. item._resyncLighSource(_this);
  21593. }
  21594. return deleted;
  21595. };
  21596. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21597. var item = array_1[_i];
  21598. item._resyncLighSource(this);
  21599. }
  21600. };
  21601. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21602. var _this = this;
  21603. var oldPush = array.push;
  21604. array.push = function () {
  21605. var items = [];
  21606. for (var _i = 0; _i < arguments.length; _i++) {
  21607. items[_i] = arguments[_i];
  21608. }
  21609. var result = oldPush.apply(array, items);
  21610. _this._resyncMeshes();
  21611. return result;
  21612. };
  21613. var oldSplice = array.splice;
  21614. array.splice = function (index, deleteCount) {
  21615. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21616. _this._resyncMeshes();
  21617. return deleted;
  21618. };
  21619. this._resyncMeshes();
  21620. };
  21621. Light.prototype._resyncMeshes = function () {
  21622. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21623. var mesh = _a[_i];
  21624. mesh._resyncLighSource(this);
  21625. }
  21626. };
  21627. /**
  21628. * Forces the meshes to update their light related information in their rendering used effects
  21629. * @hidden Internal Use Only
  21630. */
  21631. Light.prototype._markMeshesAsLightDirty = function () {
  21632. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21633. var mesh = _a[_i];
  21634. if (mesh._lightSources.indexOf(this) !== -1) {
  21635. mesh._markSubMeshesAsLightDirty();
  21636. }
  21637. }
  21638. };
  21639. /**
  21640. * Recomputes the cached photometric scale if needed.
  21641. */
  21642. Light.prototype._computePhotometricScale = function () {
  21643. this._photometricScale = this._getPhotometricScale();
  21644. this.getScene().resetCachedMaterial();
  21645. };
  21646. /**
  21647. * Returns the Photometric Scale according to the light type and intensity mode.
  21648. */
  21649. Light.prototype._getPhotometricScale = function () {
  21650. var photometricScale = 0.0;
  21651. var lightTypeID = this.getTypeID();
  21652. //get photometric mode
  21653. var photometricMode = this.intensityMode;
  21654. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21655. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21656. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21657. }
  21658. else {
  21659. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21660. }
  21661. }
  21662. //compute photometric scale
  21663. switch (lightTypeID) {
  21664. case Light.LIGHTTYPEID_POINTLIGHT:
  21665. case Light.LIGHTTYPEID_SPOTLIGHT:
  21666. switch (photometricMode) {
  21667. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21668. photometricScale = 1.0 / (4.0 * Math.PI);
  21669. break;
  21670. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21671. photometricScale = 1.0;
  21672. break;
  21673. case Light.INTENSITYMODE_LUMINANCE:
  21674. photometricScale = this.radius * this.radius;
  21675. break;
  21676. }
  21677. break;
  21678. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21679. switch (photometricMode) {
  21680. case Light.INTENSITYMODE_ILLUMINANCE:
  21681. photometricScale = 1.0;
  21682. break;
  21683. case Light.INTENSITYMODE_LUMINANCE:
  21684. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21685. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21686. var apexAngleRadians = this.radius;
  21687. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21688. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21689. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21690. photometricScale = solidAngle;
  21691. break;
  21692. }
  21693. break;
  21694. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21695. // No fall off in hemisperic light.
  21696. photometricScale = 1.0;
  21697. break;
  21698. }
  21699. return photometricScale;
  21700. };
  21701. /**
  21702. * Reorder the light in the scene according to their defined priority.
  21703. * @hidden Internal Use Only
  21704. */
  21705. Light.prototype._reorderLightsInScene = function () {
  21706. var scene = this.getScene();
  21707. if (this._renderPriority != 0) {
  21708. scene.requireLightSorting = true;
  21709. }
  21710. this.getScene().sortLightsByPriority();
  21711. };
  21712. //lightmapMode Consts
  21713. /**
  21714. * If every light affecting the material is in this lightmapMode,
  21715. * material.lightmapTexture adds or multiplies
  21716. * (depends on material.useLightmapAsShadowmap)
  21717. * after every other light calculations.
  21718. */
  21719. Light.LIGHTMAP_DEFAULT = 0;
  21720. /**
  21721. * material.lightmapTexture as only diffuse lighting from this light
  21722. * adds only specular lighting from this light
  21723. * adds dynamic shadows
  21724. */
  21725. Light.LIGHTMAP_SPECULAR = 1;
  21726. /**
  21727. * material.lightmapTexture as only lighting
  21728. * no light calculation from this light
  21729. * only adds dynamic shadows from this light
  21730. */
  21731. Light.LIGHTMAP_SHADOWSONLY = 2;
  21732. // Intensity Mode Consts
  21733. /**
  21734. * Each light type uses the default quantity according to its type:
  21735. * point/spot lights use luminous intensity
  21736. * directional lights use illuminance
  21737. */
  21738. Light.INTENSITYMODE_AUTOMATIC = 0;
  21739. /**
  21740. * lumen (lm)
  21741. */
  21742. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  21743. /**
  21744. * candela (lm/sr)
  21745. */
  21746. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21747. /**
  21748. * lux (lm/m^2)
  21749. */
  21750. Light.INTENSITYMODE_ILLUMINANCE = 3;
  21751. /**
  21752. * nit (cd/m^2)
  21753. */
  21754. Light.INTENSITYMODE_LUMINANCE = 4;
  21755. // Light types ids const.
  21756. /**
  21757. * Light type const id of the point light.
  21758. */
  21759. Light.LIGHTTYPEID_POINTLIGHT = 0;
  21760. /**
  21761. * Light type const id of the directional light.
  21762. */
  21763. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21764. /**
  21765. * Light type const id of the spot light.
  21766. */
  21767. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  21768. /**
  21769. * Light type const id of the hemispheric light.
  21770. */
  21771. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21772. __decorate([
  21773. BABYLON.serializeAsColor3()
  21774. ], Light.prototype, "diffuse", void 0);
  21775. __decorate([
  21776. BABYLON.serializeAsColor3()
  21777. ], Light.prototype, "specular", void 0);
  21778. __decorate([
  21779. BABYLON.serialize()
  21780. ], Light.prototype, "intensity", void 0);
  21781. __decorate([
  21782. BABYLON.serialize()
  21783. ], Light.prototype, "range", void 0);
  21784. __decorate([
  21785. BABYLON.serialize()
  21786. ], Light.prototype, "intensityMode", null);
  21787. __decorate([
  21788. BABYLON.serialize()
  21789. ], Light.prototype, "radius", null);
  21790. __decorate([
  21791. BABYLON.serialize()
  21792. ], Light.prototype, "_renderPriority", void 0);
  21793. __decorate([
  21794. BABYLON.expandToProperty("_reorderLightsInScene")
  21795. ], Light.prototype, "renderPriority", void 0);
  21796. __decorate([
  21797. BABYLON.serialize("shadowEnabled")
  21798. ], Light.prototype, "_shadowEnabled", void 0);
  21799. __decorate([
  21800. BABYLON.serialize("excludeWithLayerMask")
  21801. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21802. __decorate([
  21803. BABYLON.serialize("includeOnlyWithLayerMask")
  21804. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21805. __decorate([
  21806. BABYLON.serialize("lightmapMode")
  21807. ], Light.prototype, "_lightmapMode", void 0);
  21808. return Light;
  21809. }(BABYLON.Node));
  21810. BABYLON.Light = Light;
  21811. })(BABYLON || (BABYLON = {}));
  21812. //# sourceMappingURL=babylon.light.js.map
  21813. var BABYLON;
  21814. (function (BABYLON) {
  21815. var Camera = /** @class */ (function (_super) {
  21816. __extends(Camera, _super);
  21817. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21818. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21819. var _this = _super.call(this, name, scene) || this;
  21820. /**
  21821. * The vector the camera should consider as up.
  21822. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21823. */
  21824. _this.upVector = BABYLON.Vector3.Up();
  21825. _this.orthoLeft = null;
  21826. _this.orthoRight = null;
  21827. _this.orthoBottom = null;
  21828. _this.orthoTop = null;
  21829. /**
  21830. * FOV is set in Radians. (default is 0.8)
  21831. */
  21832. _this.fov = 0.8;
  21833. _this.minZ = 1;
  21834. _this.maxZ = 10000.0;
  21835. _this.inertia = 0.9;
  21836. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21837. _this.isIntermediate = false;
  21838. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21839. /**
  21840. * Restricts the camera to viewing objects with the same layerMask.
  21841. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21842. */
  21843. _this.layerMask = 0x0FFFFFFF;
  21844. /**
  21845. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21846. */
  21847. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21848. // Camera rig members
  21849. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21850. _this._rigCameras = new Array();
  21851. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21852. _this._skipRendering = false;
  21853. _this.customRenderTargets = new Array();
  21854. // Observables
  21855. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21856. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21857. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21858. _this.onRestoreStateObservable = new BABYLON.Observable();
  21859. // Cache
  21860. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21861. _this._projectionMatrix = new BABYLON.Matrix();
  21862. _this._doNotComputeProjectionMatrix = false;
  21863. _this._worldMatrix = BABYLON.Matrix.Identity();
  21864. _this._postProcesses = new Array();
  21865. _this._transformMatrix = BABYLON.Matrix.Zero();
  21866. _this._activeMeshes = new BABYLON.SmartArray(256);
  21867. _this._globalPosition = BABYLON.Vector3.Zero();
  21868. _this._refreshFrustumPlanes = true;
  21869. _this.getScene().addCamera(_this);
  21870. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  21871. _this.getScene().activeCamera = _this;
  21872. }
  21873. _this.position = position;
  21874. return _this;
  21875. }
  21876. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21877. get: function () {
  21878. return Camera._PERSPECTIVE_CAMERA;
  21879. },
  21880. enumerable: true,
  21881. configurable: true
  21882. });
  21883. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21884. get: function () {
  21885. return Camera._ORTHOGRAPHIC_CAMERA;
  21886. },
  21887. enumerable: true,
  21888. configurable: true
  21889. });
  21890. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21891. /**
  21892. * This is the default FOV mode for perspective cameras.
  21893. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21894. *
  21895. */
  21896. get: function () {
  21897. return Camera._FOVMODE_VERTICAL_FIXED;
  21898. },
  21899. enumerable: true,
  21900. configurable: true
  21901. });
  21902. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21903. /**
  21904. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21905. *
  21906. */
  21907. get: function () {
  21908. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21914. get: function () {
  21915. return Camera._RIG_MODE_NONE;
  21916. },
  21917. enumerable: true,
  21918. configurable: true
  21919. });
  21920. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21921. get: function () {
  21922. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21923. },
  21924. enumerable: true,
  21925. configurable: true
  21926. });
  21927. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21928. get: function () {
  21929. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21930. },
  21931. enumerable: true,
  21932. configurable: true
  21933. });
  21934. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21935. get: function () {
  21936. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21937. },
  21938. enumerable: true,
  21939. configurable: true
  21940. });
  21941. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21942. get: function () {
  21943. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21944. },
  21945. enumerable: true,
  21946. configurable: true
  21947. });
  21948. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21949. get: function () {
  21950. return Camera._RIG_MODE_VR;
  21951. },
  21952. enumerable: true,
  21953. configurable: true
  21954. });
  21955. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21956. get: function () {
  21957. return Camera._RIG_MODE_WEBVR;
  21958. },
  21959. enumerable: true,
  21960. configurable: true
  21961. });
  21962. /**
  21963. * Store current camera state (fov, position, etc..)
  21964. */
  21965. Camera.prototype.storeState = function () {
  21966. this._stateStored = true;
  21967. this._storedFov = this.fov;
  21968. return this;
  21969. };
  21970. /**
  21971. * Restores the camera state values if it has been stored. You must call storeState() first
  21972. */
  21973. Camera.prototype._restoreStateValues = function () {
  21974. if (!this._stateStored) {
  21975. return false;
  21976. }
  21977. this.fov = this._storedFov;
  21978. return true;
  21979. };
  21980. /**
  21981. * Restored camera state. You must call storeState() first
  21982. */
  21983. Camera.prototype.restoreState = function () {
  21984. if (this._restoreStateValues()) {
  21985. this.onRestoreStateObservable.notifyObservers(this);
  21986. return true;
  21987. }
  21988. return false;
  21989. };
  21990. Camera.prototype.getClassName = function () {
  21991. return "Camera";
  21992. };
  21993. /**
  21994. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21995. */
  21996. Camera.prototype.toString = function (fullDetails) {
  21997. var ret = "Name: " + this.name;
  21998. ret += ", type: " + this.getClassName();
  21999. if (this.animations) {
  22000. for (var i = 0; i < this.animations.length; i++) {
  22001. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22002. }
  22003. }
  22004. if (fullDetails) {
  22005. }
  22006. return ret;
  22007. };
  22008. Object.defineProperty(Camera.prototype, "globalPosition", {
  22009. get: function () {
  22010. return this._globalPosition;
  22011. },
  22012. enumerable: true,
  22013. configurable: true
  22014. });
  22015. Camera.prototype.getActiveMeshes = function () {
  22016. return this._activeMeshes;
  22017. };
  22018. Camera.prototype.isActiveMesh = function (mesh) {
  22019. return (this._activeMeshes.indexOf(mesh) !== -1);
  22020. };
  22021. /**
  22022. * Is this camera ready to be used/rendered
  22023. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22024. * @return true if the camera is ready
  22025. */
  22026. Camera.prototype.isReady = function (completeCheck) {
  22027. if (completeCheck === void 0) { completeCheck = false; }
  22028. if (completeCheck) {
  22029. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22030. var pp = _a[_i];
  22031. if (pp && !pp.isReady()) {
  22032. return false;
  22033. }
  22034. }
  22035. }
  22036. return _super.prototype.isReady.call(this, completeCheck);
  22037. };
  22038. //Cache
  22039. Camera.prototype._initCache = function () {
  22040. _super.prototype._initCache.call(this);
  22041. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22042. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22043. this._cache.mode = undefined;
  22044. this._cache.minZ = undefined;
  22045. this._cache.maxZ = undefined;
  22046. this._cache.fov = undefined;
  22047. this._cache.fovMode = undefined;
  22048. this._cache.aspectRatio = undefined;
  22049. this._cache.orthoLeft = undefined;
  22050. this._cache.orthoRight = undefined;
  22051. this._cache.orthoBottom = undefined;
  22052. this._cache.orthoTop = undefined;
  22053. this._cache.renderWidth = undefined;
  22054. this._cache.renderHeight = undefined;
  22055. };
  22056. Camera.prototype._updateCache = function (ignoreParentClass) {
  22057. if (!ignoreParentClass) {
  22058. _super.prototype._updateCache.call(this);
  22059. }
  22060. this._cache.position.copyFrom(this.position);
  22061. this._cache.upVector.copyFrom(this.upVector);
  22062. };
  22063. // Synchronized
  22064. Camera.prototype._isSynchronized = function () {
  22065. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22066. };
  22067. Camera.prototype._isSynchronizedViewMatrix = function () {
  22068. if (!_super.prototype._isSynchronized.call(this))
  22069. return false;
  22070. return this._cache.position.equals(this.position)
  22071. && this._cache.upVector.equals(this.upVector)
  22072. && this.isSynchronizedWithParent();
  22073. };
  22074. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22075. var check = this._cache.mode === this.mode
  22076. && this._cache.minZ === this.minZ
  22077. && this._cache.maxZ === this.maxZ;
  22078. if (!check) {
  22079. return false;
  22080. }
  22081. var engine = this.getEngine();
  22082. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22083. check = this._cache.fov === this.fov
  22084. && this._cache.fovMode === this.fovMode
  22085. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22086. }
  22087. else {
  22088. check = this._cache.orthoLeft === this.orthoLeft
  22089. && this._cache.orthoRight === this.orthoRight
  22090. && this._cache.orthoBottom === this.orthoBottom
  22091. && this._cache.orthoTop === this.orthoTop
  22092. && this._cache.renderWidth === engine.getRenderWidth()
  22093. && this._cache.renderHeight === engine.getRenderHeight();
  22094. }
  22095. return check;
  22096. };
  22097. // Controls
  22098. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22099. };
  22100. Camera.prototype.detachControl = function (element) {
  22101. };
  22102. Camera.prototype.update = function () {
  22103. this._checkInputs();
  22104. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22105. this._updateRigCameras();
  22106. }
  22107. };
  22108. Camera.prototype._checkInputs = function () {
  22109. this.onAfterCheckInputsObservable.notifyObservers(this);
  22110. };
  22111. Object.defineProperty(Camera.prototype, "rigCameras", {
  22112. get: function () {
  22113. return this._rigCameras;
  22114. },
  22115. enumerable: true,
  22116. configurable: true
  22117. });
  22118. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22119. get: function () {
  22120. return this._rigPostProcess;
  22121. },
  22122. enumerable: true,
  22123. configurable: true
  22124. });
  22125. /**
  22126. * Internal, gets the first post proces.
  22127. * @returns the first post process to be run on this camera.
  22128. */
  22129. Camera.prototype._getFirstPostProcess = function () {
  22130. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22131. if (this._postProcesses[ppIndex] !== null) {
  22132. return this._postProcesses[ppIndex];
  22133. }
  22134. }
  22135. return null;
  22136. };
  22137. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22138. // invalidate framebuffer
  22139. var firstPostProcess = this._getFirstPostProcess();
  22140. if (firstPostProcess) {
  22141. firstPostProcess.markTextureDirty();
  22142. }
  22143. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22144. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22145. var cam = this._rigCameras[i];
  22146. var rigPostProcess = cam._rigPostProcess;
  22147. // for VR rig, there does not have to be a post process
  22148. if (rigPostProcess) {
  22149. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22150. if (isPass) {
  22151. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22152. cam.isIntermediate = this._postProcesses.length === 0;
  22153. }
  22154. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22155. rigPostProcess.markTextureDirty();
  22156. }
  22157. else {
  22158. cam._postProcesses = this._postProcesses.slice(0);
  22159. }
  22160. }
  22161. };
  22162. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22163. if (insertAt === void 0) { insertAt = null; }
  22164. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22165. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22166. return 0;
  22167. }
  22168. if (insertAt == null || insertAt < 0) {
  22169. this._postProcesses.push(postProcess);
  22170. }
  22171. else if (this._postProcesses[insertAt] === null) {
  22172. this._postProcesses[insertAt] = postProcess;
  22173. }
  22174. else {
  22175. this._postProcesses.splice(insertAt, 0, postProcess);
  22176. }
  22177. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22178. return this._postProcesses.indexOf(postProcess);
  22179. };
  22180. Camera.prototype.detachPostProcess = function (postProcess) {
  22181. var idx = this._postProcesses.indexOf(postProcess);
  22182. if (idx !== -1) {
  22183. this._postProcesses[idx] = null;
  22184. }
  22185. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22186. };
  22187. Camera.prototype.getWorldMatrix = function () {
  22188. if (this._isSynchronizedViewMatrix()) {
  22189. return this._worldMatrix;
  22190. }
  22191. // Getting the the view matrix will also compute the world matrix.
  22192. this.getViewMatrix();
  22193. return this._worldMatrix;
  22194. };
  22195. Camera.prototype._getViewMatrix = function () {
  22196. return BABYLON.Matrix.Identity();
  22197. };
  22198. Camera.prototype.getViewMatrix = function (force) {
  22199. if (!force && this._isSynchronizedViewMatrix()) {
  22200. return this._computedViewMatrix;
  22201. }
  22202. this.updateCache();
  22203. this._computedViewMatrix = this._getViewMatrix();
  22204. this._currentRenderId = this.getScene().getRenderId();
  22205. this._childRenderId = this._currentRenderId;
  22206. this._refreshFrustumPlanes = true;
  22207. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22208. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22209. }
  22210. this.onViewMatrixChangedObservable.notifyObservers(this);
  22211. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22212. return this._computedViewMatrix;
  22213. };
  22214. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22215. this._doNotComputeProjectionMatrix = true;
  22216. if (projection !== undefined) {
  22217. this._projectionMatrix = projection;
  22218. }
  22219. };
  22220. ;
  22221. Camera.prototype.unfreezeProjectionMatrix = function () {
  22222. this._doNotComputeProjectionMatrix = false;
  22223. };
  22224. ;
  22225. Camera.prototype.getProjectionMatrix = function (force) {
  22226. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22227. return this._projectionMatrix;
  22228. }
  22229. // Cache
  22230. this._cache.mode = this.mode;
  22231. this._cache.minZ = this.minZ;
  22232. this._cache.maxZ = this.maxZ;
  22233. // Matrix
  22234. this._refreshFrustumPlanes = true;
  22235. var engine = this.getEngine();
  22236. var scene = this.getScene();
  22237. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22238. this._cache.fov = this.fov;
  22239. this._cache.fovMode = this.fovMode;
  22240. this._cache.aspectRatio = engine.getAspectRatio(this);
  22241. if (this.minZ <= 0) {
  22242. this.minZ = 0.1;
  22243. }
  22244. if (scene.useRightHandedSystem) {
  22245. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22246. }
  22247. else {
  22248. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22249. }
  22250. }
  22251. else {
  22252. var halfWidth = engine.getRenderWidth() / 2.0;
  22253. var halfHeight = engine.getRenderHeight() / 2.0;
  22254. if (scene.useRightHandedSystem) {
  22255. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22256. }
  22257. else {
  22258. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22259. }
  22260. this._cache.orthoLeft = this.orthoLeft;
  22261. this._cache.orthoRight = this.orthoRight;
  22262. this._cache.orthoBottom = this.orthoBottom;
  22263. this._cache.orthoTop = this.orthoTop;
  22264. this._cache.renderWidth = engine.getRenderWidth();
  22265. this._cache.renderHeight = engine.getRenderHeight();
  22266. }
  22267. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22268. return this._projectionMatrix;
  22269. };
  22270. Camera.prototype.getTranformationMatrix = function () {
  22271. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22272. return this._transformMatrix;
  22273. };
  22274. Camera.prototype.updateFrustumPlanes = function () {
  22275. if (!this._refreshFrustumPlanes) {
  22276. return;
  22277. }
  22278. this.getTranformationMatrix();
  22279. if (!this._frustumPlanes) {
  22280. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22281. }
  22282. else {
  22283. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22284. }
  22285. this._refreshFrustumPlanes = false;
  22286. };
  22287. Camera.prototype.isInFrustum = function (target) {
  22288. this.updateFrustumPlanes();
  22289. return target.isInFrustum(this._frustumPlanes);
  22290. };
  22291. Camera.prototype.isCompletelyInFrustum = function (target) {
  22292. this.updateFrustumPlanes();
  22293. return target.isCompletelyInFrustum(this._frustumPlanes);
  22294. };
  22295. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22296. if (length === void 0) { length = 100; }
  22297. if (!transform) {
  22298. transform = this.getWorldMatrix();
  22299. }
  22300. if (!origin) {
  22301. origin = this.position;
  22302. }
  22303. var forward = new BABYLON.Vector3(0, 0, 1);
  22304. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22305. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22306. return new BABYLON.Ray(origin, direction, length);
  22307. };
  22308. /**
  22309. * Releases resources associated with this node.
  22310. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22311. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22312. */
  22313. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22314. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22315. // Observables
  22316. this.onViewMatrixChangedObservable.clear();
  22317. this.onProjectionMatrixChangedObservable.clear();
  22318. this.onAfterCheckInputsObservable.clear();
  22319. this.onRestoreStateObservable.clear();
  22320. // Inputs
  22321. if (this.inputs) {
  22322. this.inputs.clear();
  22323. }
  22324. // Animations
  22325. this.getScene().stopAnimation(this);
  22326. // Remove from scene
  22327. this.getScene().removeCamera(this);
  22328. while (this._rigCameras.length > 0) {
  22329. var camera = this._rigCameras.pop();
  22330. if (camera) {
  22331. camera.dispose();
  22332. }
  22333. }
  22334. // Postprocesses
  22335. if (this._rigPostProcess) {
  22336. this._rigPostProcess.dispose(this);
  22337. this._rigPostProcess = null;
  22338. this._postProcesses = [];
  22339. }
  22340. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22341. this._rigPostProcess = null;
  22342. this._postProcesses = [];
  22343. }
  22344. else {
  22345. var i = this._postProcesses.length;
  22346. while (--i >= 0) {
  22347. var postProcess = this._postProcesses[i];
  22348. if (postProcess) {
  22349. postProcess.dispose(this);
  22350. }
  22351. }
  22352. }
  22353. // Render targets
  22354. var i = this.customRenderTargets.length;
  22355. while (--i >= 0) {
  22356. this.customRenderTargets[i].dispose();
  22357. }
  22358. this.customRenderTargets = [];
  22359. // Active Meshes
  22360. this._activeMeshes.dispose();
  22361. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22362. };
  22363. Object.defineProperty(Camera.prototype, "leftCamera", {
  22364. // ---- Camera rigs section ----
  22365. get: function () {
  22366. if (this._rigCameras.length < 1) {
  22367. return null;
  22368. }
  22369. return this._rigCameras[0];
  22370. },
  22371. enumerable: true,
  22372. configurable: true
  22373. });
  22374. Object.defineProperty(Camera.prototype, "rightCamera", {
  22375. get: function () {
  22376. if (this._rigCameras.length < 2) {
  22377. return null;
  22378. }
  22379. return this._rigCameras[1];
  22380. },
  22381. enumerable: true,
  22382. configurable: true
  22383. });
  22384. Camera.prototype.getLeftTarget = function () {
  22385. if (this._rigCameras.length < 1) {
  22386. return null;
  22387. }
  22388. return this._rigCameras[0].getTarget();
  22389. };
  22390. Camera.prototype.getRightTarget = function () {
  22391. if (this._rigCameras.length < 2) {
  22392. return null;
  22393. }
  22394. return this._rigCameras[1].getTarget();
  22395. };
  22396. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22397. if (this.cameraRigMode === mode) {
  22398. return;
  22399. }
  22400. while (this._rigCameras.length > 0) {
  22401. var camera = this._rigCameras.pop();
  22402. if (camera) {
  22403. camera.dispose();
  22404. }
  22405. }
  22406. this.cameraRigMode = mode;
  22407. this._cameraRigParams = {};
  22408. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22409. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22410. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22411. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22412. // create the rig cameras, unless none
  22413. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22414. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22415. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22416. if (leftCamera && rightCamera) {
  22417. this._rigCameras.push(leftCamera);
  22418. this._rigCameras.push(rightCamera);
  22419. }
  22420. }
  22421. switch (this.cameraRigMode) {
  22422. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22423. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22424. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22425. break;
  22426. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22427. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22428. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22429. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22430. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22431. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22432. break;
  22433. case Camera.RIG_MODE_VR:
  22434. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22435. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22436. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22437. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22438. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22439. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22440. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22441. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22442. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22443. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22444. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22445. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22446. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22447. if (metrics.compensateDistortion) {
  22448. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22449. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22450. }
  22451. break;
  22452. case Camera.RIG_MODE_WEBVR:
  22453. if (rigParams.vrDisplay) {
  22454. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22455. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22456. //Left eye
  22457. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22458. this._rigCameras[0].setCameraRigParameter("left", true);
  22459. //leaving this for future reference
  22460. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22461. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22462. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22463. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22464. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22465. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22466. this._rigCameras[0].parent = this;
  22467. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22468. //Right eye
  22469. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22470. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22471. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22472. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22473. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22474. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22475. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22476. this._rigCameras[1].parent = this;
  22477. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22478. if (Camera.UseAlternateWebVRRendering) {
  22479. this._rigCameras[1]._skipRendering = true;
  22480. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22481. }
  22482. }
  22483. break;
  22484. }
  22485. this._cascadePostProcessesToRigCams();
  22486. this.update();
  22487. };
  22488. Camera.prototype._getVRProjectionMatrix = function () {
  22489. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22490. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22491. return this._projectionMatrix;
  22492. };
  22493. Camera.prototype._updateCameraRotationMatrix = function () {
  22494. //Here for WebVR
  22495. };
  22496. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22497. //Here for WebVR
  22498. };
  22499. /**
  22500. * This function MUST be overwritten by the different WebVR cameras available.
  22501. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22502. */
  22503. Camera.prototype._getWebVRProjectionMatrix = function () {
  22504. return BABYLON.Matrix.Identity();
  22505. };
  22506. /**
  22507. * This function MUST be overwritten by the different WebVR cameras available.
  22508. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22509. */
  22510. Camera.prototype._getWebVRViewMatrix = function () {
  22511. return BABYLON.Matrix.Identity();
  22512. };
  22513. Camera.prototype.setCameraRigParameter = function (name, value) {
  22514. if (!this._cameraRigParams) {
  22515. this._cameraRigParams = {};
  22516. }
  22517. this._cameraRigParams[name] = value;
  22518. //provisionnally:
  22519. if (name === "interaxialDistance") {
  22520. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22521. }
  22522. };
  22523. /**
  22524. * needs to be overridden by children so sub has required properties to be copied
  22525. */
  22526. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22527. return null;
  22528. };
  22529. /**
  22530. * May need to be overridden by children
  22531. */
  22532. Camera.prototype._updateRigCameras = function () {
  22533. for (var i = 0; i < this._rigCameras.length; i++) {
  22534. this._rigCameras[i].minZ = this.minZ;
  22535. this._rigCameras[i].maxZ = this.maxZ;
  22536. this._rigCameras[i].fov = this.fov;
  22537. }
  22538. // only update viewport when ANAGLYPH
  22539. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22540. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22541. }
  22542. };
  22543. Camera.prototype._setupInputs = function () {
  22544. };
  22545. Camera.prototype.serialize = function () {
  22546. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22547. // Type
  22548. serializationObject.type = this.getClassName();
  22549. // Parent
  22550. if (this.parent) {
  22551. serializationObject.parentId = this.parent.id;
  22552. }
  22553. if (this.inputs) {
  22554. this.inputs.serialize(serializationObject);
  22555. }
  22556. // Animations
  22557. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22558. serializationObject.ranges = this.serializeAnimationRanges();
  22559. return serializationObject;
  22560. };
  22561. Camera.prototype.clone = function (name) {
  22562. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22563. };
  22564. Camera.prototype.getDirection = function (localAxis) {
  22565. var result = BABYLON.Vector3.Zero();
  22566. this.getDirectionToRef(localAxis, result);
  22567. return result;
  22568. };
  22569. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22570. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22571. };
  22572. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22573. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22574. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22575. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22576. interaxial_distance: interaxial_distance,
  22577. isStereoscopicSideBySide: isStereoscopicSideBySide
  22578. });
  22579. if (constructorFunc) {
  22580. return constructorFunc;
  22581. }
  22582. // Default to universal camera
  22583. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22584. };
  22585. Camera.prototype.computeWorldMatrix = function () {
  22586. return this.getWorldMatrix();
  22587. };
  22588. Camera.Parse = function (parsedCamera, scene) {
  22589. var type = parsedCamera.type;
  22590. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22591. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22592. // Parent
  22593. if (parsedCamera.parentId) {
  22594. camera._waitingParentId = parsedCamera.parentId;
  22595. }
  22596. //If camera has an input manager, let it parse inputs settings
  22597. if (camera.inputs) {
  22598. camera.inputs.parse(parsedCamera);
  22599. camera._setupInputs();
  22600. }
  22601. if (camera.setPosition) { // need to force position
  22602. camera.position.copyFromFloats(0, 0, 0);
  22603. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22604. }
  22605. // Target
  22606. if (parsedCamera.target) {
  22607. if (camera.setTarget) {
  22608. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22609. }
  22610. }
  22611. // Apply 3d rig, when found
  22612. if (parsedCamera.cameraRigMode) {
  22613. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22614. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22615. }
  22616. // Animations
  22617. if (parsedCamera.animations) {
  22618. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22619. var parsedAnimation = parsedCamera.animations[animationIndex];
  22620. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22621. }
  22622. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22623. }
  22624. if (parsedCamera.autoAnimate) {
  22625. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22626. }
  22627. return camera;
  22628. };
  22629. // Statics
  22630. Camera._PERSPECTIVE_CAMERA = 0;
  22631. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22632. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22633. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22634. Camera._RIG_MODE_NONE = 0;
  22635. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22636. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22637. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22638. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22639. Camera._RIG_MODE_VR = 20;
  22640. Camera._RIG_MODE_WEBVR = 21;
  22641. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22642. Camera.UseAlternateWebVRRendering = false;
  22643. __decorate([
  22644. BABYLON.serializeAsVector3()
  22645. ], Camera.prototype, "position", void 0);
  22646. __decorate([
  22647. BABYLON.serializeAsVector3()
  22648. ], Camera.prototype, "upVector", void 0);
  22649. __decorate([
  22650. BABYLON.serialize()
  22651. ], Camera.prototype, "orthoLeft", void 0);
  22652. __decorate([
  22653. BABYLON.serialize()
  22654. ], Camera.prototype, "orthoRight", void 0);
  22655. __decorate([
  22656. BABYLON.serialize()
  22657. ], Camera.prototype, "orthoBottom", void 0);
  22658. __decorate([
  22659. BABYLON.serialize()
  22660. ], Camera.prototype, "orthoTop", void 0);
  22661. __decorate([
  22662. BABYLON.serialize()
  22663. ], Camera.prototype, "fov", void 0);
  22664. __decorate([
  22665. BABYLON.serialize()
  22666. ], Camera.prototype, "minZ", void 0);
  22667. __decorate([
  22668. BABYLON.serialize()
  22669. ], Camera.prototype, "maxZ", void 0);
  22670. __decorate([
  22671. BABYLON.serialize()
  22672. ], Camera.prototype, "inertia", void 0);
  22673. __decorate([
  22674. BABYLON.serialize()
  22675. ], Camera.prototype, "mode", void 0);
  22676. __decorate([
  22677. BABYLON.serialize()
  22678. ], Camera.prototype, "layerMask", void 0);
  22679. __decorate([
  22680. BABYLON.serialize()
  22681. ], Camera.prototype, "fovMode", void 0);
  22682. __decorate([
  22683. BABYLON.serialize()
  22684. ], Camera.prototype, "cameraRigMode", void 0);
  22685. __decorate([
  22686. BABYLON.serialize()
  22687. ], Camera.prototype, "interaxialDistance", void 0);
  22688. __decorate([
  22689. BABYLON.serialize()
  22690. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22691. return Camera;
  22692. }(BABYLON.Node));
  22693. BABYLON.Camera = Camera;
  22694. })(BABYLON || (BABYLON = {}));
  22695. //# sourceMappingURL=babylon.camera.js.map
  22696. var BABYLON;
  22697. (function (BABYLON) {
  22698. var RenderingManager = /** @class */ (function () {
  22699. function RenderingManager(scene) {
  22700. /**
  22701. * Hidden
  22702. */
  22703. this._useSceneAutoClearSetup = false;
  22704. this._renderingGroups = new Array();
  22705. this._autoClearDepthStencil = {};
  22706. this._customOpaqueSortCompareFn = {};
  22707. this._customAlphaTestSortCompareFn = {};
  22708. this._customTransparentSortCompareFn = {};
  22709. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  22710. this._scene = scene;
  22711. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22712. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22713. }
  22714. }
  22715. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22716. if (depth === void 0) { depth = true; }
  22717. if (stencil === void 0) { stencil = true; }
  22718. if (this._depthStencilBufferAlreadyCleaned) {
  22719. return;
  22720. }
  22721. this._scene.getEngine().clear(null, false, depth, stencil);
  22722. this._depthStencilBufferAlreadyCleaned = true;
  22723. };
  22724. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22725. // Update the observable context (not null as it only goes away on dispose)
  22726. var info = this._renderingGroupInfo;
  22727. info.scene = this._scene;
  22728. info.camera = this._scene.activeCamera;
  22729. // Dispatch sprites
  22730. if (renderSprites) {
  22731. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22732. var manager = this._scene.spriteManagers[index];
  22733. this.dispatchSprites(manager);
  22734. }
  22735. }
  22736. // Render
  22737. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22738. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22739. var renderingGroup = this._renderingGroups[index];
  22740. if (!renderingGroup)
  22741. continue;
  22742. var renderingGroupMask = Math.pow(2, index);
  22743. info.renderingGroupId = index;
  22744. // Before Observable
  22745. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22746. // Clear depth/stencil if needed
  22747. if (RenderingManager.AUTOCLEAR) {
  22748. var autoClear = this._useSceneAutoClearSetup ?
  22749. this._scene.getAutoClearDepthStencilSetup(index) :
  22750. this._autoClearDepthStencil[index];
  22751. if (autoClear && autoClear.autoClear) {
  22752. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22753. }
  22754. }
  22755. // Render
  22756. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  22757. var step = _a[_i];
  22758. step.action(index);
  22759. }
  22760. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22761. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  22762. var step = _c[_b];
  22763. step.action(index);
  22764. }
  22765. // After Observable
  22766. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  22767. }
  22768. };
  22769. RenderingManager.prototype.reset = function () {
  22770. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22771. var renderingGroup = this._renderingGroups[index];
  22772. if (renderingGroup) {
  22773. renderingGroup.prepare();
  22774. }
  22775. }
  22776. };
  22777. RenderingManager.prototype.dispose = function () {
  22778. this.freeRenderingGroups();
  22779. this._renderingGroups.length = 0;
  22780. this._renderingGroupInfo = null;
  22781. };
  22782. /**
  22783. * Clear the info related to rendering groups preventing retention points during dispose.
  22784. */
  22785. RenderingManager.prototype.freeRenderingGroups = function () {
  22786. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22787. var renderingGroup = this._renderingGroups[index];
  22788. if (renderingGroup) {
  22789. renderingGroup.dispose();
  22790. }
  22791. }
  22792. };
  22793. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22794. if (this._renderingGroups[renderingGroupId] === undefined) {
  22795. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22796. }
  22797. };
  22798. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22799. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22800. this._prepareRenderingGroup(renderingGroupId);
  22801. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22802. };
  22803. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22804. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22805. this._prepareRenderingGroup(renderingGroupId);
  22806. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22807. };
  22808. /**
  22809. * @param subMesh The submesh to dispatch
  22810. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22811. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22812. */
  22813. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22814. if (mesh === undefined) {
  22815. mesh = subMesh.getMesh();
  22816. }
  22817. var renderingGroupId = mesh.renderingGroupId || 0;
  22818. this._prepareRenderingGroup(renderingGroupId);
  22819. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22820. };
  22821. /**
  22822. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22823. * This allowed control for front to back rendering or reversly depending of the special needs.
  22824. *
  22825. * @param renderingGroupId The rendering group id corresponding to its index
  22826. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22827. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22828. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22829. */
  22830. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22831. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22832. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22833. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22834. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22835. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22836. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22837. if (this._renderingGroups[renderingGroupId]) {
  22838. var group = this._renderingGroups[renderingGroupId];
  22839. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22840. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22841. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22842. }
  22843. };
  22844. /**
  22845. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22846. *
  22847. * @param renderingGroupId The rendering group id corresponding to its index
  22848. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22849. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22850. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22851. */
  22852. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22853. if (depth === void 0) { depth = true; }
  22854. if (stencil === void 0) { stencil = true; }
  22855. this._autoClearDepthStencil[renderingGroupId] = {
  22856. autoClear: autoClearDepthStencil,
  22857. depth: depth,
  22858. stencil: stencil
  22859. };
  22860. };
  22861. /**
  22862. * Gets the current auto clear configuration for one rendering group of the rendering
  22863. * manager.
  22864. * @param index the rendering group index to get the information for
  22865. * @returns The auto clear setup for the requested rendering group
  22866. */
  22867. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  22868. return this._autoClearDepthStencil[index];
  22869. };
  22870. /**
  22871. * The max id used for rendering groups (not included)
  22872. */
  22873. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22874. /**
  22875. * The min id used for rendering groups (included)
  22876. */
  22877. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22878. /**
  22879. * Used to globally prevent autoclearing scenes.
  22880. */
  22881. RenderingManager.AUTOCLEAR = true;
  22882. return RenderingManager;
  22883. }());
  22884. BABYLON.RenderingManager = RenderingManager;
  22885. })(BABYLON || (BABYLON = {}));
  22886. //# sourceMappingURL=babylon.renderingManager.js.map
  22887. var BABYLON;
  22888. (function (BABYLON) {
  22889. var RenderingGroup = /** @class */ (function () {
  22890. /**
  22891. * Creates a new rendering group.
  22892. * @param index The rendering group index
  22893. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22894. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22895. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22896. */
  22897. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22898. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22899. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22900. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22901. this.index = index;
  22902. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22903. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22904. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22905. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22906. this._particleSystems = new BABYLON.SmartArray(256);
  22907. this._spriteManagers = new BABYLON.SmartArray(256);
  22908. this._edgesRenderers = new BABYLON.SmartArray(16);
  22909. this._scene = scene;
  22910. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22911. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22912. this.transparentSortCompareFn = transparentSortCompareFn;
  22913. }
  22914. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22915. /**
  22916. * Set the opaque sort comparison function.
  22917. * If null the sub meshes will be render in the order they were created
  22918. */
  22919. set: function (value) {
  22920. this._opaqueSortCompareFn = value;
  22921. if (value) {
  22922. this._renderOpaque = this.renderOpaqueSorted;
  22923. }
  22924. else {
  22925. this._renderOpaque = RenderingGroup.renderUnsorted;
  22926. }
  22927. },
  22928. enumerable: true,
  22929. configurable: true
  22930. });
  22931. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22932. /**
  22933. * Set the alpha test sort comparison function.
  22934. * If null the sub meshes will be render in the order they were created
  22935. */
  22936. set: function (value) {
  22937. this._alphaTestSortCompareFn = value;
  22938. if (value) {
  22939. this._renderAlphaTest = this.renderAlphaTestSorted;
  22940. }
  22941. else {
  22942. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22943. }
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22949. /**
  22950. * Set the transparent sort comparison function.
  22951. * If null the sub meshes will be render in the order they were created
  22952. */
  22953. set: function (value) {
  22954. if (value) {
  22955. this._transparentSortCompareFn = value;
  22956. }
  22957. else {
  22958. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22959. }
  22960. this._renderTransparent = this.renderTransparentSorted;
  22961. },
  22962. enumerable: true,
  22963. configurable: true
  22964. });
  22965. /**
  22966. * Render all the sub meshes contained in the group.
  22967. * @param customRenderFunction Used to override the default render behaviour of the group.
  22968. * @returns true if rendered some submeshes.
  22969. */
  22970. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22971. if (customRenderFunction) {
  22972. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22973. return;
  22974. }
  22975. var engine = this._scene.getEngine();
  22976. // Depth only
  22977. if (this._depthOnlySubMeshes.length !== 0) {
  22978. engine.setColorWrite(false);
  22979. this._renderAlphaTest(this._depthOnlySubMeshes);
  22980. engine.setColorWrite(true);
  22981. }
  22982. // Opaque
  22983. if (this._opaqueSubMeshes.length !== 0) {
  22984. this._renderOpaque(this._opaqueSubMeshes);
  22985. }
  22986. // Alpha test
  22987. if (this._alphaTestSubMeshes.length !== 0) {
  22988. this._renderAlphaTest(this._alphaTestSubMeshes);
  22989. }
  22990. var stencilState = engine.getStencilBuffer();
  22991. engine.setStencilBuffer(false);
  22992. // Sprites
  22993. if (renderSprites) {
  22994. this._renderSprites();
  22995. }
  22996. // Particles
  22997. if (renderParticles) {
  22998. this._renderParticles(activeMeshes);
  22999. }
  23000. if (this.onBeforeTransparentRendering) {
  23001. this.onBeforeTransparentRendering();
  23002. }
  23003. // Transparent
  23004. if (this._transparentSubMeshes.length !== 0) {
  23005. this._renderTransparent(this._transparentSubMeshes);
  23006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23007. }
  23008. // Set back stencil to false in case it changes before the edge renderer.
  23009. engine.setStencilBuffer(false);
  23010. // Edges
  23011. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23012. this._edgesRenderers.data[edgesRendererIndex].render();
  23013. }
  23014. // Restore Stencil state.
  23015. engine.setStencilBuffer(stencilState);
  23016. };
  23017. /**
  23018. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23019. * @param subMeshes The submeshes to render
  23020. */
  23021. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23022. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23023. };
  23024. /**
  23025. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23026. * @param subMeshes The submeshes to render
  23027. */
  23028. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23029. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23030. };
  23031. /**
  23032. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23033. * @param subMeshes The submeshes to render
  23034. */
  23035. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23036. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23037. };
  23038. /**
  23039. * Renders the submeshes in a specified order.
  23040. * @param subMeshes The submeshes to sort before render
  23041. * @param sortCompareFn The comparison function use to sort
  23042. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23043. * @param transparent Specifies to activate blending if true
  23044. */
  23045. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23046. var subIndex = 0;
  23047. var subMesh;
  23048. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23049. for (; subIndex < subMeshes.length; subIndex++) {
  23050. subMesh = subMeshes.data[subIndex];
  23051. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23052. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23053. }
  23054. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23055. if (sortCompareFn) {
  23056. sortedArray.sort(sortCompareFn);
  23057. }
  23058. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23059. subMesh = sortedArray[subIndex];
  23060. if (transparent) {
  23061. var material = subMesh.getMaterial();
  23062. if (material && material.needDepthPrePass) {
  23063. var engine = material.getScene().getEngine();
  23064. engine.setColorWrite(false);
  23065. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23066. subMesh.render(false);
  23067. engine.setColorWrite(true);
  23068. }
  23069. }
  23070. subMesh.render(transparent);
  23071. }
  23072. };
  23073. /**
  23074. * Renders the submeshes in the order they were dispatched (no sort applied).
  23075. * @param subMeshes The submeshes to render
  23076. */
  23077. RenderingGroup.renderUnsorted = function (subMeshes) {
  23078. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23079. var submesh = subMeshes.data[subIndex];
  23080. submesh.render(false);
  23081. }
  23082. };
  23083. /**
  23084. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23085. * are rendered back to front if in the same alpha index.
  23086. *
  23087. * @param a The first submesh
  23088. * @param b The second submesh
  23089. * @returns The result of the comparison
  23090. */
  23091. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23092. // Alpha index first
  23093. if (a._alphaIndex > b._alphaIndex) {
  23094. return 1;
  23095. }
  23096. if (a._alphaIndex < b._alphaIndex) {
  23097. return -1;
  23098. }
  23099. // Then distance to camera
  23100. return RenderingGroup.backToFrontSortCompare(a, b);
  23101. };
  23102. /**
  23103. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23104. * are rendered back to front.
  23105. *
  23106. * @param a The first submesh
  23107. * @param b The second submesh
  23108. * @returns The result of the comparison
  23109. */
  23110. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23111. // Then distance to camera
  23112. if (a._distanceToCamera < b._distanceToCamera) {
  23113. return 1;
  23114. }
  23115. if (a._distanceToCamera > b._distanceToCamera) {
  23116. return -1;
  23117. }
  23118. return 0;
  23119. };
  23120. /**
  23121. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23122. * are rendered front to back (prevent overdraw).
  23123. *
  23124. * @param a The first submesh
  23125. * @param b The second submesh
  23126. * @returns The result of the comparison
  23127. */
  23128. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23129. // Then distance to camera
  23130. if (a._distanceToCamera < b._distanceToCamera) {
  23131. return -1;
  23132. }
  23133. if (a._distanceToCamera > b._distanceToCamera) {
  23134. return 1;
  23135. }
  23136. return 0;
  23137. };
  23138. /**
  23139. * Resets the different lists of submeshes to prepare a new frame.
  23140. */
  23141. RenderingGroup.prototype.prepare = function () {
  23142. this._opaqueSubMeshes.reset();
  23143. this._transparentSubMeshes.reset();
  23144. this._alphaTestSubMeshes.reset();
  23145. this._depthOnlySubMeshes.reset();
  23146. this._particleSystems.reset();
  23147. this._spriteManagers.reset();
  23148. this._edgesRenderers.reset();
  23149. };
  23150. RenderingGroup.prototype.dispose = function () {
  23151. this._opaqueSubMeshes.dispose();
  23152. this._transparentSubMeshes.dispose();
  23153. this._alphaTestSubMeshes.dispose();
  23154. this._depthOnlySubMeshes.dispose();
  23155. this._particleSystems.dispose();
  23156. this._spriteManagers.dispose();
  23157. this._edgesRenderers.dispose();
  23158. };
  23159. /**
  23160. * Inserts the submesh in its correct queue depending on its material.
  23161. * @param subMesh The submesh to dispatch
  23162. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23163. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23164. */
  23165. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23166. // Get mesh and materials if not provided
  23167. if (mesh === undefined) {
  23168. mesh = subMesh.getMesh();
  23169. }
  23170. if (material === undefined) {
  23171. material = subMesh.getMaterial();
  23172. }
  23173. if (material === null || material === undefined) {
  23174. return;
  23175. }
  23176. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23177. this._transparentSubMeshes.push(subMesh);
  23178. }
  23179. else if (material.needAlphaTesting()) { // Alpha test
  23180. if (material.needDepthPrePass) {
  23181. this._depthOnlySubMeshes.push(subMesh);
  23182. }
  23183. this._alphaTestSubMeshes.push(subMesh);
  23184. }
  23185. else {
  23186. if (material.needDepthPrePass) {
  23187. this._depthOnlySubMeshes.push(subMesh);
  23188. }
  23189. this._opaqueSubMeshes.push(subMesh); // Opaque
  23190. }
  23191. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23192. this._edgesRenderers.push(mesh._edgesRenderer);
  23193. }
  23194. };
  23195. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23196. this._spriteManagers.push(spriteManager);
  23197. };
  23198. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23199. this._particleSystems.push(particleSystem);
  23200. };
  23201. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23202. if (this._particleSystems.length === 0) {
  23203. return;
  23204. }
  23205. // Particles
  23206. var activeCamera = this._scene.activeCamera;
  23207. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23208. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23209. var particleSystem = this._particleSystems.data[particleIndex];
  23210. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23211. continue;
  23212. }
  23213. var emitter = particleSystem.emitter;
  23214. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23215. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23216. }
  23217. }
  23218. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23219. };
  23220. RenderingGroup.prototype._renderSprites = function () {
  23221. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23222. return;
  23223. }
  23224. // Sprites
  23225. var activeCamera = this._scene.activeCamera;
  23226. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23227. for (var id = 0; id < this._spriteManagers.length; id++) {
  23228. var spriteManager = this._spriteManagers.data[id];
  23229. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23230. spriteManager.render();
  23231. }
  23232. }
  23233. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23234. };
  23235. return RenderingGroup;
  23236. }());
  23237. BABYLON.RenderingGroup = RenderingGroup;
  23238. })(BABYLON || (BABYLON = {}));
  23239. //# sourceMappingURL=babylon.renderingGroup.js.map
  23240. var BABYLON;
  23241. (function (BABYLON) {
  23242. /**
  23243. * Groups all the scene component constants in one place to ease maintenance.
  23244. * @hidden
  23245. */
  23246. var SceneComponentConstants = /** @class */ (function () {
  23247. function SceneComponentConstants() {
  23248. }
  23249. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23250. SceneComponentConstants.NAME_LAYER = "Layer";
  23251. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23252. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23253. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23254. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23255. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23256. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23257. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23258. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23259. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23260. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23261. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23262. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23263. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23264. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23265. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23266. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23267. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23268. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23269. return SceneComponentConstants;
  23270. }());
  23271. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23272. /**
  23273. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23274. * @hidden
  23275. */
  23276. var Stage = /** @class */ (function (_super) {
  23277. __extends(Stage, _super);
  23278. /**
  23279. * Hide ctor from the rest of the world.
  23280. * @param items The items to add.
  23281. */
  23282. function Stage(items) {
  23283. return _super.apply(this, items) || this;
  23284. }
  23285. /**
  23286. * Creates a new Stage.
  23287. * @returns A new instance of a Stage
  23288. */
  23289. Stage.Create = function () {
  23290. return Object.create(Stage.prototype);
  23291. };
  23292. /**
  23293. * Registers a step in an ordered way in the targeted stage.
  23294. * @param index Defines the position to register the step in
  23295. * @param component Defines the component attached to the step
  23296. * @param action Defines the action to launch during the step
  23297. */
  23298. Stage.prototype.registerStep = function (index, component, action) {
  23299. var i = 0;
  23300. var maxIndex = Number.MAX_VALUE;
  23301. for (; i < this.length && i < maxIndex; i++) {
  23302. var step = this[i];
  23303. maxIndex = step.index;
  23304. }
  23305. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23306. };
  23307. /**
  23308. * Clears all the steps from the stage.
  23309. */
  23310. Stage.prototype.clear = function () {
  23311. this.length = 0;
  23312. };
  23313. return Stage;
  23314. }(Array));
  23315. BABYLON.Stage = Stage;
  23316. })(BABYLON || (BABYLON = {}));
  23317. //# sourceMappingURL=babylon.sceneComponent.js.map
  23318. var BABYLON;
  23319. (function (BABYLON) {
  23320. /**
  23321. * Base class of the scene acting as a container for the different elements composing a scene.
  23322. * This class is dynamically extended by the different components of the scene increasing
  23323. * flexibility and reducing coupling
  23324. */
  23325. var AbstractScene = /** @class */ (function () {
  23326. function AbstractScene() {
  23327. /** All of the cameras added to this scene
  23328. * @see http://doc.babylonjs.com/babylon101/cameras
  23329. */
  23330. this.cameras = new Array();
  23331. /**
  23332. * All of the lights added to this scene
  23333. * @see http://doc.babylonjs.com/babylon101/lights
  23334. */
  23335. this.lights = new Array();
  23336. /**
  23337. * All of the (abstract) meshes added to this scene
  23338. */
  23339. this.meshes = new Array();
  23340. /**
  23341. * The list of skeletons added to the scene
  23342. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23343. */
  23344. this.skeletons = new Array();
  23345. /**
  23346. * All of the particle systems added to this scene
  23347. * @see http://doc.babylonjs.com/babylon101/particles
  23348. */
  23349. this.particleSystems = new Array();
  23350. /**
  23351. * Gets a list of Animations associated with the scene
  23352. */
  23353. this.animations = [];
  23354. /**
  23355. * All of the animation groups added to this scene
  23356. * @see http://doc.babylonjs.com/how_to/group
  23357. */
  23358. this.animationGroups = new Array();
  23359. /**
  23360. * All of the multi-materials added to this scene
  23361. * @see http://doc.babylonjs.com/how_to/multi_materials
  23362. */
  23363. this.multiMaterials = new Array();
  23364. /**
  23365. * All of the materials added to this scene
  23366. * @see http://doc.babylonjs.com/babylon101/materials
  23367. */
  23368. this.materials = new Array();
  23369. /**
  23370. * The list of morph target managers added to the scene
  23371. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23372. */
  23373. this.morphTargetManagers = new Array();
  23374. /**
  23375. * The list of geometries used in the scene.
  23376. */
  23377. this.geometries = new Array();
  23378. /**
  23379. * All of the tranform nodes added to this scene
  23380. * @see http://doc.babylonjs.com/how_to/transformnode
  23381. */
  23382. this.transformNodes = new Array();
  23383. /**
  23384. * ActionManagers available on the scene.
  23385. */
  23386. this.actionManagers = new Array();
  23387. /**
  23388. * Sounds to keep.
  23389. */
  23390. this.sounds = new Array();
  23391. /**
  23392. * Textures to keep.
  23393. */
  23394. this.textures = new Array();
  23395. }
  23396. /**
  23397. * Adds a parser in the list of available ones
  23398. * @param name Defines the name of the parser
  23399. * @param parser Defines the parser to add
  23400. */
  23401. AbstractScene.AddParser = function (name, parser) {
  23402. this._BabylonFileParsers[name] = parser;
  23403. };
  23404. /**
  23405. * Gets a general parser from the list of avaialble ones
  23406. * @param name Defines the name of the parser
  23407. * @returns the requested parser or null
  23408. */
  23409. AbstractScene.GetParser = function (name) {
  23410. if (this._BabylonFileParsers[name]) {
  23411. return this._BabylonFileParsers[name];
  23412. }
  23413. return null;
  23414. };
  23415. /**
  23416. * Adds n individual parser in the list of available ones
  23417. * @param name Defines the name of the parser
  23418. * @param parser Defines the parser to add
  23419. */
  23420. AbstractScene.AddIndividualParser = function (name, parser) {
  23421. this._IndividualBabylonFileParsers[name] = parser;
  23422. };
  23423. /**
  23424. * Gets an individual parser from the list of avaialble ones
  23425. * @param name Defines the name of the parser
  23426. * @returns the requested parser or null
  23427. */
  23428. AbstractScene.GetIndividualParser = function (name) {
  23429. if (this._IndividualBabylonFileParsers[name]) {
  23430. return this._IndividualBabylonFileParsers[name];
  23431. }
  23432. return null;
  23433. };
  23434. /**
  23435. * Parser json data and populate both a scene and its associated container object
  23436. * @param jsonData Defines the data to parse
  23437. * @param scene Defines the scene to parse the data for
  23438. * @param container Defines the container attached to the parsing sequence
  23439. * @param rootUrl Defines the root url of the data
  23440. */
  23441. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23442. for (var parserName in this._BabylonFileParsers) {
  23443. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23444. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23445. }
  23446. }
  23447. };
  23448. /**
  23449. * Stores the list of available parsers in the application.
  23450. */
  23451. AbstractScene._BabylonFileParsers = {};
  23452. /**
  23453. * Stores the list of available individual parsers in the application.
  23454. */
  23455. AbstractScene._IndividualBabylonFileParsers = {};
  23456. return AbstractScene;
  23457. }());
  23458. BABYLON.AbstractScene = AbstractScene;
  23459. })(BABYLON || (BABYLON = {}));
  23460. //# sourceMappingURL=babylon.abstractScene.js.map
  23461. var BABYLON;
  23462. (function (BABYLON) {
  23463. /** @hidden */
  23464. var ClickInfo = /** @class */ (function () {
  23465. function ClickInfo() {
  23466. this._singleClick = false;
  23467. this._doubleClick = false;
  23468. this._hasSwiped = false;
  23469. this._ignore = false;
  23470. }
  23471. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23472. get: function () {
  23473. return this._singleClick;
  23474. },
  23475. set: function (b) {
  23476. this._singleClick = b;
  23477. },
  23478. enumerable: true,
  23479. configurable: true
  23480. });
  23481. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23482. get: function () {
  23483. return this._doubleClick;
  23484. },
  23485. set: function (b) {
  23486. this._doubleClick = b;
  23487. },
  23488. enumerable: true,
  23489. configurable: true
  23490. });
  23491. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23492. get: function () {
  23493. return this._hasSwiped;
  23494. },
  23495. set: function (b) {
  23496. this._hasSwiped = b;
  23497. },
  23498. enumerable: true,
  23499. configurable: true
  23500. });
  23501. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23502. get: function () {
  23503. return this._ignore;
  23504. },
  23505. set: function (b) {
  23506. this._ignore = b;
  23507. },
  23508. enumerable: true,
  23509. configurable: true
  23510. });
  23511. return ClickInfo;
  23512. }());
  23513. /**
  23514. * This class is used by the onRenderingGroupObservable
  23515. */
  23516. var RenderingGroupInfo = /** @class */ (function () {
  23517. function RenderingGroupInfo() {
  23518. }
  23519. return RenderingGroupInfo;
  23520. }());
  23521. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23522. /**
  23523. * Represents a scene to be rendered by the engine.
  23524. * @see http://doc.babylonjs.com/features/scene
  23525. */
  23526. var Scene = /** @class */ (function (_super) {
  23527. __extends(Scene, _super);
  23528. /**
  23529. * Creates a new Scene
  23530. * @param engine defines the engine to use to render this scene
  23531. */
  23532. function Scene(engine) {
  23533. var _this = _super.call(this) || this;
  23534. // Members
  23535. /**
  23536. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23537. */
  23538. _this.autoClear = true;
  23539. /**
  23540. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23541. */
  23542. _this.autoClearDepthAndStencil = true;
  23543. /**
  23544. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23545. */
  23546. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23547. /**
  23548. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23549. */
  23550. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23551. _this._forceWireframe = false;
  23552. _this._forcePointsCloud = false;
  23553. /**
  23554. * Gets or sets a boolean indicating if animations are enabled
  23555. */
  23556. _this.animationsEnabled = true;
  23557. _this._animationPropertiesOverride = null;
  23558. /**
  23559. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23560. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23561. */
  23562. _this.useConstantAnimationDeltaTime = false;
  23563. /**
  23564. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23565. * Please note that it requires to run a ray cast through the scene on every frame
  23566. */
  23567. _this.constantlyUpdateMeshUnderPointer = false;
  23568. /**
  23569. * Defines the HTML cursor to use when hovering over interactive elements
  23570. */
  23571. _this.hoverCursor = "pointer";
  23572. /**
  23573. * Defines the HTML default cursor to use (empty by default)
  23574. */
  23575. _this.defaultCursor = "";
  23576. /**
  23577. * This is used to call preventDefault() on pointer down
  23578. * in order to block unwanted artifacts like system double clicks
  23579. */
  23580. _this.preventDefaultOnPointerDown = true;
  23581. // Metadata
  23582. /**
  23583. * Gets or sets user defined metadata
  23584. */
  23585. _this.metadata = null;
  23586. /**
  23587. * Use this array to add regular expressions used to disable offline support for specific urls
  23588. */
  23589. _this.disableOfflineSupportExceptionRules = new Array();
  23590. /**
  23591. * An event triggered when the scene is disposed.
  23592. */
  23593. _this.onDisposeObservable = new BABYLON.Observable();
  23594. _this._onDisposeObserver = null;
  23595. /**
  23596. * An event triggered before rendering the scene (right after animations and physics)
  23597. */
  23598. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23599. _this._onBeforeRenderObserver = null;
  23600. /**
  23601. * An event triggered after rendering the scene
  23602. */
  23603. _this.onAfterRenderObservable = new BABYLON.Observable();
  23604. _this._onAfterRenderObserver = null;
  23605. /**
  23606. * An event triggered before animating the scene
  23607. */
  23608. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23609. /**
  23610. * An event triggered after animations processing
  23611. */
  23612. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23613. /**
  23614. * An event triggered before draw calls are ready to be sent
  23615. */
  23616. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23617. /**
  23618. * An event triggered after draw calls have been sent
  23619. */
  23620. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23621. /**
  23622. * An event triggered when physic simulation is about to be run
  23623. */
  23624. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23625. /**
  23626. * An event triggered when physic simulation has been done
  23627. */
  23628. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered when the scene is ready
  23631. */
  23632. _this.onReadyObservable = new BABYLON.Observable();
  23633. /**
  23634. * An event triggered before rendering a camera
  23635. */
  23636. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23637. _this._onBeforeCameraRenderObserver = null;
  23638. /**
  23639. * An event triggered after rendering a camera
  23640. */
  23641. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23642. _this._onAfterCameraRenderObserver = null;
  23643. /**
  23644. * An event triggered when active meshes evaluation is about to start
  23645. */
  23646. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23647. /**
  23648. * An event triggered when active meshes evaluation is done
  23649. */
  23650. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23651. /**
  23652. * An event triggered when particles rendering is about to start
  23653. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23654. */
  23655. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered when particles rendering is done
  23658. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23659. */
  23660. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23661. /**
  23662. * An event triggered when sprites rendering is about to start
  23663. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23664. */
  23665. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23666. /**
  23667. * An event triggered when sprites rendering is done
  23668. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23669. */
  23670. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23671. /**
  23672. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23673. */
  23674. _this.onDataLoadedObservable = new BABYLON.Observable();
  23675. /**
  23676. * An event triggered when a camera is created
  23677. */
  23678. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  23679. /**
  23680. * An event triggered when a camera is removed
  23681. */
  23682. _this.onCameraRemovedObservable = new BABYLON.Observable();
  23683. /**
  23684. * An event triggered when a light is created
  23685. */
  23686. _this.onNewLightAddedObservable = new BABYLON.Observable();
  23687. /**
  23688. * An event triggered when a light is removed
  23689. */
  23690. _this.onLightRemovedObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when a geometry is created
  23693. */
  23694. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered when a geometry is removed
  23697. */
  23698. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered when a transform node is created
  23701. */
  23702. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered when a transform node is removed
  23705. */
  23706. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when a mesh is created
  23709. */
  23710. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when a mesh is removed
  23713. */
  23714. _this.onMeshRemovedObservable = new BABYLON.Observable();
  23715. /**
  23716. * An event triggered when render targets are about to be rendered
  23717. * Can happen multiple times per frame.
  23718. */
  23719. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23720. /**
  23721. * An event triggered when render targets were rendered.
  23722. * Can happen multiple times per frame.
  23723. */
  23724. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered before calculating deterministic simulation step
  23727. */
  23728. _this.onBeforeStepObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered after calculating deterministic simulation step
  23731. */
  23732. _this.onAfterStepObservable = new BABYLON.Observable();
  23733. /**
  23734. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  23735. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23736. * 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)
  23737. */
  23738. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  23739. /**
  23740. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  23741. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23742. * 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)
  23743. */
  23744. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  23745. // Animations
  23746. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23747. /**
  23748. * 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).
  23749. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23750. */
  23751. _this.onPrePointerObservable = new BABYLON.Observable();
  23752. /**
  23753. * Observable event triggered each time an input event is received from the rendering canvas
  23754. */
  23755. _this.onPointerObservable = new BABYLON.Observable();
  23756. _this._meshPickProceed = false;
  23757. _this._currentPickResult = null;
  23758. _this._previousPickResult = null;
  23759. _this._totalPointersPressed = 0;
  23760. _this._doubleClickOccured = false;
  23761. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23762. _this.cameraToUseForPointers = null;
  23763. _this._pointerX = 0;
  23764. _this._pointerY = 0;
  23765. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23766. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23767. _this._startingPointerTime = 0;
  23768. _this._previousStartingPointerTime = 0;
  23769. _this._pointerCaptures = {};
  23770. // Deterministic lockstep
  23771. _this._timeAccumulator = 0;
  23772. _this._currentStepId = 0;
  23773. _this._currentInternalStep = 0;
  23774. // Keyboard
  23775. /**
  23776. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23777. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23778. */
  23779. _this.onPreKeyboardObservable = new BABYLON.Observable();
  23780. /**
  23781. * Observable event triggered each time an keyboard event is received from the hosting window
  23782. */
  23783. _this.onKeyboardObservable = new BABYLON.Observable();
  23784. // Coordinates system
  23785. _this._useRightHandedSystem = false;
  23786. // Fog
  23787. _this._fogEnabled = true;
  23788. _this._fogMode = Scene.FOGMODE_NONE;
  23789. /**
  23790. * Gets or sets the fog color to use
  23791. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23792. */
  23793. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23794. /**
  23795. * Gets or sets the fog density to use
  23796. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23797. */
  23798. _this.fogDensity = 0.1;
  23799. /**
  23800. * Gets or sets the fog start distance to use
  23801. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23802. */
  23803. _this.fogStart = 0;
  23804. /**
  23805. * Gets or sets the fog end distance to use
  23806. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23807. */
  23808. _this.fogEnd = 1000.0;
  23809. // Lights
  23810. _this._shadowsEnabled = true;
  23811. _this._lightsEnabled = true;
  23812. /** All of the active cameras added to this scene. */
  23813. _this.activeCameras = new Array();
  23814. // Textures
  23815. _this._texturesEnabled = true;
  23816. // Particles
  23817. /**
  23818. * Gets or sets a boolean indicating if particles are enabled on this scene
  23819. */
  23820. _this.particlesEnabled = true;
  23821. // Sprites
  23822. /**
  23823. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23824. */
  23825. _this.spritesEnabled = true;
  23826. /**
  23827. * All of the sprite managers added to this scene
  23828. * @see http://doc.babylonjs.com/babylon101/sprites
  23829. */
  23830. _this.spriteManagers = new Array();
  23831. // Skeletons
  23832. _this._skeletonsEnabled = true;
  23833. // Lens flares
  23834. /**
  23835. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23836. */
  23837. _this.lensFlaresEnabled = true;
  23838. // Collisions
  23839. /**
  23840. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23841. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23842. */
  23843. _this.collisionsEnabled = true;
  23844. /**
  23845. * Defines the gravity applied to this scene (used only for collisions)
  23846. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23847. */
  23848. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23849. // Postprocesses
  23850. /**
  23851. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23852. */
  23853. _this.postProcessesEnabled = true;
  23854. /**
  23855. * The list of postprocesses added to the scene
  23856. */
  23857. _this.postProcesses = new Array();
  23858. // Customs render targets
  23859. /**
  23860. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23861. */
  23862. _this.renderTargetsEnabled = true;
  23863. /**
  23864. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23865. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23866. */
  23867. _this.dumpNextRenderTargets = false;
  23868. /**
  23869. * The list of user defined render targets added to the scene
  23870. */
  23871. _this.customRenderTargets = new Array();
  23872. /**
  23873. * Gets the list of meshes imported to the scene through SceneLoader
  23874. */
  23875. _this.importedMeshesFiles = new Array();
  23876. // Probes
  23877. /**
  23878. * Gets or sets a boolean indicating if probes are enabled on this scene
  23879. */
  23880. _this.probesEnabled = true;
  23881. /**
  23882. * The list of reflection probes added to the scene
  23883. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23884. */
  23885. _this.reflectionProbes = new Array();
  23886. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23887. // Procedural textures
  23888. /**
  23889. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23890. */
  23891. _this.proceduralTexturesEnabled = true;
  23892. /**
  23893. * The list of procedural textures added to the scene
  23894. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23895. */
  23896. _this.proceduralTextures = new Array();
  23897. /**
  23898. * The list of sound tracks added to the scene
  23899. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23900. */
  23901. _this.soundTracks = new Array();
  23902. _this._audioEnabled = true;
  23903. _this._headphone = false;
  23904. // Performance counters
  23905. _this._totalVertices = new BABYLON.PerfCounter();
  23906. /** @hidden */
  23907. _this._activeIndices = new BABYLON.PerfCounter();
  23908. /** @hidden */
  23909. _this._activeParticles = new BABYLON.PerfCounter();
  23910. /** @hidden */
  23911. _this._activeBones = new BABYLON.PerfCounter();
  23912. _this._animationTime = 0;
  23913. /**
  23914. * Gets or sets a general scale for animation speed
  23915. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23916. */
  23917. _this.animationTimeScale = 1;
  23918. _this._renderId = 0;
  23919. _this._executeWhenReadyTimeoutId = -1;
  23920. _this._intermediateRendering = false;
  23921. _this._viewUpdateFlag = -1;
  23922. _this._projectionUpdateFlag = -1;
  23923. _this._alternateViewUpdateFlag = -1;
  23924. _this._alternateProjectionUpdateFlag = -1;
  23925. /** @hidden */
  23926. _this._toBeDisposed = new BABYLON.SmartArray(256);
  23927. _this._activeRequests = new Array();
  23928. _this._pendingData = new Array();
  23929. _this._isDisposed = false;
  23930. /**
  23931. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23932. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23933. */
  23934. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  23935. _this._activeMeshes = new BABYLON.SmartArray(256);
  23936. _this._processedMaterials = new BABYLON.SmartArray(256);
  23937. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23938. /** @hidden */
  23939. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  23940. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23941. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23942. /** @hidden */
  23943. _this._activeAnimatables = new Array();
  23944. _this._transformMatrix = BABYLON.Matrix.Zero();
  23945. _this._useAlternateCameraConfiguration = false;
  23946. _this._alternateRendering = false;
  23947. /**
  23948. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23949. * This is useful if there are more lights that the maximum simulteanous authorized
  23950. */
  23951. _this.requireLightSorting = false;
  23952. _this._depthRenderer = {};
  23953. /**
  23954. * Backing store of defined scene components.
  23955. */
  23956. _this._components = [];
  23957. /**
  23958. * Backing store of defined scene components.
  23959. */
  23960. _this._serializableComponents = [];
  23961. /**
  23962. * List of components to register on the next registration step.
  23963. */
  23964. _this._transientComponents = [];
  23965. /**
  23966. * Defines the actions happening before camera updates.
  23967. */
  23968. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  23969. /**
  23970. * Defines the actions happening during the per mesh ready checks.
  23971. */
  23972. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  23973. /**
  23974. * Defines the actions happening before evaluate active mesh checks.
  23975. */
  23976. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  23977. /**
  23978. * Defines the actions happening during the evaluate sub mesh checks.
  23979. */
  23980. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  23981. /**
  23982. * Defines the actions happening during the active mesh stage.
  23983. */
  23984. _this._activeMeshStage = BABYLON.Stage.Create();
  23985. /**
  23986. * Defines the actions happening during the per camera render target step.
  23987. */
  23988. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  23989. /**
  23990. * Defines the actions happening just before the active camera is drawing.
  23991. */
  23992. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  23993. /**
  23994. * Defines the actions happening just before a rendering group is drawing.
  23995. */
  23996. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  23997. /**
  23998. * Defines the actions happening just after a rendering group has been drawn.
  23999. */
  24000. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24001. /**
  24002. * Defines the actions happening just after the active camera has been drawn.
  24003. */
  24004. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24005. _this._activeMeshesFrozen = false;
  24006. /** @hidden */
  24007. _this._allowPostProcessClear = true;
  24008. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24009. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24010. _this._engine.scenes.push(_this);
  24011. _this._uid = null;
  24012. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24013. if (BABYLON.PostProcessManager) {
  24014. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24015. }
  24016. if (BABYLON.OutlineRenderer) {
  24017. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24018. }
  24019. if (BABYLON.Tools.IsWindowObjectExist()) {
  24020. _this.attachControl();
  24021. }
  24022. //simplification queue
  24023. if (BABYLON.SimplificationQueue) {
  24024. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24025. }
  24026. //collision coordinator initialization. For now legacy per default.
  24027. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24028. // Uniform Buffer
  24029. _this._createUbo();
  24030. // Default Image processing definition
  24031. if (BABYLON.ImageProcessingConfiguration) {
  24032. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24033. }
  24034. return _this;
  24035. }
  24036. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24037. /** The fog is deactivated */
  24038. get: function () {
  24039. return Scene._FOGMODE_NONE;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24045. /** The fog density is following an exponential function */
  24046. get: function () {
  24047. return Scene._FOGMODE_EXP;
  24048. },
  24049. enumerable: true,
  24050. configurable: true
  24051. });
  24052. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24053. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24054. get: function () {
  24055. return Scene._FOGMODE_EXP2;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24061. /** The fog density is following a linear function. */
  24062. get: function () {
  24063. return Scene._FOGMODE_LINEAR;
  24064. },
  24065. enumerable: true,
  24066. configurable: true
  24067. });
  24068. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24069. /**
  24070. * Texture used in all pbr material as the reflection texture.
  24071. * As in the majority of the scene they are the same (exception for multi room and so on),
  24072. * this is easier to reference from here than from all the materials.
  24073. */
  24074. get: function () {
  24075. return this._environmentTexture;
  24076. },
  24077. /**
  24078. * Texture used in all pbr material as the reflection texture.
  24079. * As in the majority of the scene they are the same (exception for multi room and so on),
  24080. * this is easier to set here than in all the materials.
  24081. */
  24082. set: function (value) {
  24083. if (this._environmentTexture === value) {
  24084. return;
  24085. }
  24086. this._environmentTexture = value;
  24087. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24093. /**
  24094. * Default image processing configuration used either in the rendering
  24095. * Forward main pass or through the imageProcessingPostProcess if present.
  24096. * As in the majority of the scene they are the same (exception for multi camera),
  24097. * this is easier to reference from here than from all the materials and post process.
  24098. *
  24099. * No setter as we it is a shared configuration, you can set the values instead.
  24100. */
  24101. get: function () {
  24102. return this._imageProcessingConfiguration;
  24103. },
  24104. enumerable: true,
  24105. configurable: true
  24106. });
  24107. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24108. get: function () {
  24109. return this._forceWireframe;
  24110. },
  24111. /**
  24112. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24113. */
  24114. set: function (value) {
  24115. if (this._forceWireframe === value) {
  24116. return;
  24117. }
  24118. this._forceWireframe = value;
  24119. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24120. },
  24121. enumerable: true,
  24122. configurable: true
  24123. });
  24124. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24125. get: function () {
  24126. return this._forcePointsCloud;
  24127. },
  24128. /**
  24129. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24130. */
  24131. set: function (value) {
  24132. if (this._forcePointsCloud === value) {
  24133. return;
  24134. }
  24135. this._forcePointsCloud = value;
  24136. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24137. },
  24138. enumerable: true,
  24139. configurable: true
  24140. });
  24141. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24142. /**
  24143. * Gets or sets the animation properties override
  24144. */
  24145. get: function () {
  24146. return this._animationPropertiesOverride;
  24147. },
  24148. set: function (value) {
  24149. this._animationPropertiesOverride = value;
  24150. },
  24151. enumerable: true,
  24152. configurable: true
  24153. });
  24154. Object.defineProperty(Scene.prototype, "onDispose", {
  24155. /** Sets a function to be executed when this scene is disposed. */
  24156. set: function (callback) {
  24157. if (this._onDisposeObserver) {
  24158. this.onDisposeObservable.remove(this._onDisposeObserver);
  24159. }
  24160. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24161. },
  24162. enumerable: true,
  24163. configurable: true
  24164. });
  24165. Object.defineProperty(Scene.prototype, "beforeRender", {
  24166. /** Sets a function to be executed before rendering this scene */
  24167. set: function (callback) {
  24168. if (this._onBeforeRenderObserver) {
  24169. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24170. }
  24171. if (callback) {
  24172. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24173. }
  24174. },
  24175. enumerable: true,
  24176. configurable: true
  24177. });
  24178. Object.defineProperty(Scene.prototype, "afterRender", {
  24179. /** Sets a function to be executed after rendering this scene */
  24180. set: function (callback) {
  24181. if (this._onAfterRenderObserver) {
  24182. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24183. }
  24184. if (callback) {
  24185. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24186. }
  24187. },
  24188. enumerable: true,
  24189. configurable: true
  24190. });
  24191. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24192. /** Sets a function to be executed before rendering a camera*/
  24193. set: function (callback) {
  24194. if (this._onBeforeCameraRenderObserver) {
  24195. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24196. }
  24197. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24198. },
  24199. enumerable: true,
  24200. configurable: true
  24201. });
  24202. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24203. /** Sets a function to be executed after rendering a camera*/
  24204. set: function (callback) {
  24205. if (this._onAfterCameraRenderObserver) {
  24206. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24207. }
  24208. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24209. },
  24210. enumerable: true,
  24211. configurable: true
  24212. });
  24213. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24214. /**
  24215. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24216. */
  24217. get: function () {
  24218. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24224. get: function () {
  24225. return this._useRightHandedSystem;
  24226. },
  24227. /**
  24228. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24229. */
  24230. set: function (value) {
  24231. if (this._useRightHandedSystem === value) {
  24232. return;
  24233. }
  24234. this._useRightHandedSystem = value;
  24235. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24236. },
  24237. enumerable: true,
  24238. configurable: true
  24239. });
  24240. /**
  24241. * Sets the step Id used by deterministic lock step
  24242. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24243. * @param newStepId defines the step Id
  24244. */
  24245. Scene.prototype.setStepId = function (newStepId) {
  24246. this._currentStepId = newStepId;
  24247. };
  24248. ;
  24249. /**
  24250. * Gets the step Id used by deterministic lock step
  24251. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24252. * @returns the step Id
  24253. */
  24254. Scene.prototype.getStepId = function () {
  24255. return this._currentStepId;
  24256. };
  24257. ;
  24258. /**
  24259. * Gets the internal step used by deterministic lock step
  24260. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24261. * @returns the internal step
  24262. */
  24263. Scene.prototype.getInternalStep = function () {
  24264. return this._currentInternalStep;
  24265. };
  24266. ;
  24267. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24268. get: function () {
  24269. return this._fogEnabled;
  24270. },
  24271. /**
  24272. * Gets or sets a boolean indicating if fog is enabled on this scene
  24273. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24274. */
  24275. set: function (value) {
  24276. if (this._fogEnabled === value) {
  24277. return;
  24278. }
  24279. this._fogEnabled = value;
  24280. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24281. },
  24282. enumerable: true,
  24283. configurable: true
  24284. });
  24285. Object.defineProperty(Scene.prototype, "fogMode", {
  24286. get: function () {
  24287. return this._fogMode;
  24288. },
  24289. /**
  24290. * Gets or sets the fog mode to use
  24291. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24292. */
  24293. set: function (value) {
  24294. if (this._fogMode === value) {
  24295. return;
  24296. }
  24297. this._fogMode = value;
  24298. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24299. },
  24300. enumerable: true,
  24301. configurable: true
  24302. });
  24303. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24304. get: function () {
  24305. return this._shadowsEnabled;
  24306. },
  24307. /**
  24308. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24309. */
  24310. set: function (value) {
  24311. if (this._shadowsEnabled === value) {
  24312. return;
  24313. }
  24314. this._shadowsEnabled = value;
  24315. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24321. get: function () {
  24322. return this._lightsEnabled;
  24323. },
  24324. /**
  24325. * Gets or sets a boolean indicating if lights are enabled on this scene
  24326. */
  24327. set: function (value) {
  24328. if (this._lightsEnabled === value) {
  24329. return;
  24330. }
  24331. this._lightsEnabled = value;
  24332. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24338. /** The default material used on meshes when no material is affected */
  24339. get: function () {
  24340. if (!this._defaultMaterial) {
  24341. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24342. }
  24343. return this._defaultMaterial;
  24344. },
  24345. /** The default material used on meshes when no material is affected */
  24346. set: function (value) {
  24347. this._defaultMaterial = value;
  24348. },
  24349. enumerable: true,
  24350. configurable: true
  24351. });
  24352. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24353. get: function () {
  24354. return this._texturesEnabled;
  24355. },
  24356. /**
  24357. * Gets or sets a boolean indicating if textures are enabled on this scene
  24358. */
  24359. set: function (value) {
  24360. if (this._texturesEnabled === value) {
  24361. return;
  24362. }
  24363. this._texturesEnabled = value;
  24364. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24370. get: function () {
  24371. return this._skeletonsEnabled;
  24372. },
  24373. /**
  24374. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24375. */
  24376. set: function (value) {
  24377. if (this._skeletonsEnabled === value) {
  24378. return;
  24379. }
  24380. this._skeletonsEnabled = value;
  24381. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24382. },
  24383. enumerable: true,
  24384. configurable: true
  24385. });
  24386. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24387. /**
  24388. * Gets the postprocess render pipeline manager
  24389. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24390. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24391. */
  24392. get: function () {
  24393. if (!this._postProcessRenderPipelineManager) {
  24394. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24395. }
  24396. return this._postProcessRenderPipelineManager;
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24402. /**
  24403. * Gets the main soundtrack associated with the scene
  24404. */
  24405. get: function () {
  24406. if (!this._mainSoundTrack) {
  24407. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24408. }
  24409. return this._mainSoundTrack;
  24410. },
  24411. enumerable: true,
  24412. configurable: true
  24413. });
  24414. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24415. /** @hidden */
  24416. get: function () {
  24417. return this._alternateRendering;
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24423. /**
  24424. * Gets the list of frustum planes (built from the active camera)
  24425. */
  24426. get: function () {
  24427. return this._frustumPlanes;
  24428. },
  24429. enumerable: true,
  24430. configurable: true
  24431. });
  24432. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24433. /**
  24434. * Gets the current geometry buffer associated to the scene.
  24435. */
  24436. get: function () {
  24437. return this._geometryBufferRenderer;
  24438. },
  24439. /**
  24440. * Sets the current geometry buffer for the scene.
  24441. */
  24442. set: function (geometryBufferRenderer) {
  24443. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24444. this._geometryBufferRenderer = geometryBufferRenderer;
  24445. }
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. /**
  24451. * Registers the transient components if needed.
  24452. */
  24453. Scene.prototype._registerTransientComponents = function () {
  24454. // Register components that have been associated lately to the scene.
  24455. if (this._transientComponents.length > 0) {
  24456. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24457. var component = _a[_i];
  24458. component.register();
  24459. }
  24460. this._transientComponents = [];
  24461. }
  24462. };
  24463. /**
  24464. * Add a component to the scene.
  24465. * Note that the ccomponent could be registered on th next frame if this is called after
  24466. * the register component stage.
  24467. * @param component Defines the component to add to the scene
  24468. */
  24469. Scene.prototype._addComponent = function (component) {
  24470. this._components.push(component);
  24471. this._transientComponents.push(component);
  24472. var serializableComponent = component;
  24473. if (serializableComponent.addFromContainer) {
  24474. this._serializableComponents.push(serializableComponent);
  24475. }
  24476. };
  24477. /**
  24478. * Gets a component from the scene.
  24479. * @param name defines the name of the component to retrieve
  24480. * @returns the component or null if not present
  24481. */
  24482. Scene.prototype._getComponent = function (name) {
  24483. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24484. var component = _a[_i];
  24485. if (component.name === name) {
  24486. return component;
  24487. }
  24488. }
  24489. return null;
  24490. };
  24491. Object.defineProperty(Scene.prototype, "debugLayer", {
  24492. /**
  24493. * Gets the debug layer (aka Inspector) associated with the scene
  24494. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24495. */
  24496. get: function () {
  24497. if (!this._debugLayer) {
  24498. this._debugLayer = new BABYLON.DebugLayer(this);
  24499. }
  24500. return this._debugLayer;
  24501. },
  24502. enumerable: true,
  24503. configurable: true
  24504. });
  24505. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24506. /**
  24507. * Gets a boolean indicating if collisions are processed on a web worker
  24508. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24509. */
  24510. get: function () {
  24511. return this._workerCollisions;
  24512. },
  24513. set: function (enabled) {
  24514. if (!BABYLON.CollisionCoordinatorLegacy) {
  24515. return;
  24516. }
  24517. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24518. this._workerCollisions = enabled;
  24519. if (this.collisionCoordinator) {
  24520. this.collisionCoordinator.destroy();
  24521. }
  24522. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24523. this.collisionCoordinator.init(this);
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24529. /**
  24530. * Gets the octree used to boost mesh selection (picking)
  24531. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24532. */
  24533. get: function () {
  24534. return this._selectionOctree;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24540. /**
  24541. * Gets the mesh that is currently under the pointer
  24542. */
  24543. get: function () {
  24544. return this._pointerOverMesh;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. Object.defineProperty(Scene.prototype, "pointerX", {
  24550. /**
  24551. * Gets the current on-screen X position of the pointer
  24552. */
  24553. get: function () {
  24554. return this._pointerX;
  24555. },
  24556. enumerable: true,
  24557. configurable: true
  24558. });
  24559. Object.defineProperty(Scene.prototype, "pointerY", {
  24560. /**
  24561. * Gets the current on-screen Y position of the pointer
  24562. */
  24563. get: function () {
  24564. return this._pointerY;
  24565. },
  24566. enumerable: true,
  24567. configurable: true
  24568. });
  24569. /**
  24570. * Gets the cached material (ie. the latest rendered one)
  24571. * @returns the cached material
  24572. */
  24573. Scene.prototype.getCachedMaterial = function () {
  24574. return this._cachedMaterial;
  24575. };
  24576. /**
  24577. * Gets the cached effect (ie. the latest rendered one)
  24578. * @returns the cached effect
  24579. */
  24580. Scene.prototype.getCachedEffect = function () {
  24581. return this._cachedEffect;
  24582. };
  24583. /**
  24584. * Gets the cached visibility state (ie. the latest rendered one)
  24585. * @returns the cached visibility state
  24586. */
  24587. Scene.prototype.getCachedVisibility = function () {
  24588. return this._cachedVisibility;
  24589. };
  24590. /**
  24591. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24592. * @param material defines the current material
  24593. * @param effect defines the current effect
  24594. * @param visibility defines the current visibility state
  24595. * @returns true if one parameter is not cached
  24596. */
  24597. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24598. if (visibility === void 0) { visibility = 1; }
  24599. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24600. };
  24601. /**
  24602. * Gets the outline renderer associated with the scene
  24603. * @returns a OutlineRenderer
  24604. */
  24605. Scene.prototype.getOutlineRenderer = function () {
  24606. return this._outlineRenderer;
  24607. };
  24608. /**
  24609. * Gets the engine associated with the scene
  24610. * @returns an Engine
  24611. */
  24612. Scene.prototype.getEngine = function () {
  24613. return this._engine;
  24614. };
  24615. /**
  24616. * Gets the total number of vertices rendered per frame
  24617. * @returns the total number of vertices rendered per frame
  24618. */
  24619. Scene.prototype.getTotalVertices = function () {
  24620. return this._totalVertices.current;
  24621. };
  24622. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24623. /**
  24624. * Gets the performance counter for total vertices
  24625. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24626. */
  24627. get: function () {
  24628. return this._totalVertices;
  24629. },
  24630. enumerable: true,
  24631. configurable: true
  24632. });
  24633. /**
  24634. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24635. * @returns the total number of active indices rendered per frame
  24636. */
  24637. Scene.prototype.getActiveIndices = function () {
  24638. return this._activeIndices.current;
  24639. };
  24640. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24641. /**
  24642. * Gets the performance counter for active indices
  24643. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24644. */
  24645. get: function () {
  24646. return this._activeIndices;
  24647. },
  24648. enumerable: true,
  24649. configurable: true
  24650. });
  24651. /**
  24652. * Gets the total number of active particles rendered per frame
  24653. * @returns the total number of active particles rendered per frame
  24654. */
  24655. Scene.prototype.getActiveParticles = function () {
  24656. return this._activeParticles.current;
  24657. };
  24658. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24659. /**
  24660. * Gets the performance counter for active particles
  24661. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24662. */
  24663. get: function () {
  24664. return this._activeParticles;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. /**
  24670. * Gets the total number of active bones rendered per frame
  24671. * @returns the total number of active bones rendered per frame
  24672. */
  24673. Scene.prototype.getActiveBones = function () {
  24674. return this._activeBones.current;
  24675. };
  24676. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24677. /**
  24678. * Gets the performance counter for active bones
  24679. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24680. */
  24681. get: function () {
  24682. return this._activeBones;
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. /** @hidden */
  24688. Scene.prototype.getInterFramePerfCounter = function () {
  24689. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24690. return 0;
  24691. };
  24692. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24693. /** @hidden */
  24694. get: function () {
  24695. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24696. return null;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. /** @hidden */
  24702. Scene.prototype.getLastFrameDuration = function () {
  24703. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24704. return 0;
  24705. };
  24706. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24707. /** @hidden */
  24708. get: function () {
  24709. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24710. return null;
  24711. },
  24712. enumerable: true,
  24713. configurable: true
  24714. });
  24715. /** @hidden */
  24716. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24717. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24718. return 0;
  24719. };
  24720. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24721. /** @hidden */
  24722. get: function () {
  24723. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24724. return null;
  24725. },
  24726. enumerable: true,
  24727. configurable: true
  24728. });
  24729. /**
  24730. * Gets the array of active meshes
  24731. * @returns an array of AbstractMesh
  24732. */
  24733. Scene.prototype.getActiveMeshes = function () {
  24734. return this._activeMeshes;
  24735. };
  24736. /** @hidden */
  24737. Scene.prototype.getRenderTargetsDuration = function () {
  24738. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24739. return 0;
  24740. };
  24741. /** @hidden */
  24742. Scene.prototype.getRenderDuration = function () {
  24743. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24744. return 0;
  24745. };
  24746. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24747. /** @hidden */
  24748. get: function () {
  24749. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24750. return null;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. /** @hidden */
  24756. Scene.prototype.getParticlesDuration = function () {
  24757. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24758. return 0;
  24759. };
  24760. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24761. /** @hidden */
  24762. get: function () {
  24763. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24764. return null;
  24765. },
  24766. enumerable: true,
  24767. configurable: true
  24768. });
  24769. /** @hidden */
  24770. Scene.prototype.getSpritesDuration = function () {
  24771. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24772. return 0;
  24773. };
  24774. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24775. /** @hidden */
  24776. get: function () {
  24777. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24778. return null;
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. /**
  24784. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24785. * @returns a number
  24786. */
  24787. Scene.prototype.getAnimationRatio = function () {
  24788. return this._animationRatio !== undefined ? this._animationRatio : 1;
  24789. };
  24790. /**
  24791. * Gets an unique Id for the current frame
  24792. * @returns a number
  24793. */
  24794. Scene.prototype.getRenderId = function () {
  24795. return this._renderId;
  24796. };
  24797. /** Call this function if you want to manually increment the render Id*/
  24798. Scene.prototype.incrementRenderId = function () {
  24799. this._renderId++;
  24800. };
  24801. Scene.prototype._updatePointerPosition = function (evt) {
  24802. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24803. if (!canvasRect) {
  24804. return;
  24805. }
  24806. this._pointerX = evt.clientX - canvasRect.left;
  24807. this._pointerY = evt.clientY - canvasRect.top;
  24808. this._unTranslatedPointerX = this._pointerX;
  24809. this._unTranslatedPointerY = this._pointerY;
  24810. };
  24811. Scene.prototype._createUbo = function () {
  24812. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24813. this._sceneUbo.addUniform("viewProjection", 16);
  24814. this._sceneUbo.addUniform("view", 16);
  24815. };
  24816. Scene.prototype._createAlternateUbo = function () {
  24817. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24818. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24819. this._alternateSceneUbo.addUniform("view", 16);
  24820. };
  24821. // Pointers handling
  24822. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  24823. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  24824. if (result) {
  24825. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  24826. }
  24827. return result;
  24828. };
  24829. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  24830. if (pointerInfo.pickInfo) {
  24831. if (!pointerInfo.pickInfo.ray) {
  24832. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  24833. }
  24834. }
  24835. };
  24836. /**
  24837. * Use this method to simulate a pointer move on a mesh
  24838. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24839. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24840. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24841. * @returns the current scene
  24842. */
  24843. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24844. var evt = new PointerEvent("pointermove", pointerEventInit);
  24845. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  24846. return this;
  24847. }
  24848. return this._processPointerMove(pickResult, evt);
  24849. };
  24850. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24851. var canvas = this._engine.getRenderingCanvas();
  24852. if (!canvas) {
  24853. return this;
  24854. }
  24855. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24856. this.setPointerOverSprite(null);
  24857. this.setPointerOverMesh(pickResult.pickedMesh);
  24858. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24859. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24860. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24861. }
  24862. else {
  24863. canvas.style.cursor = this.hoverCursor;
  24864. }
  24865. }
  24866. else {
  24867. canvas.style.cursor = this.defaultCursor;
  24868. }
  24869. }
  24870. else {
  24871. this.setPointerOverMesh(null);
  24872. // Sprites
  24873. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24874. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24875. this.setPointerOverSprite(pickResult.pickedSprite);
  24876. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24877. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24878. }
  24879. else {
  24880. canvas.style.cursor = this.hoverCursor;
  24881. }
  24882. }
  24883. else {
  24884. this.setPointerOverSprite(null);
  24885. // Restore pointer
  24886. canvas.style.cursor = this.defaultCursor;
  24887. }
  24888. }
  24889. if (pickResult) {
  24890. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24891. if (this.onPointerMove) {
  24892. this.onPointerMove(evt, pickResult, type);
  24893. }
  24894. if (this.onPointerObservable.hasObservers()) {
  24895. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24896. this._setRayOnPointerInfo(pi);
  24897. this.onPointerObservable.notifyObservers(pi, type);
  24898. }
  24899. }
  24900. return this;
  24901. };
  24902. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  24903. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  24904. if (pickResult) {
  24905. pi.ray = pickResult.ray;
  24906. }
  24907. this.onPrePointerObservable.notifyObservers(pi, type);
  24908. if (pi.skipOnPointerObservable) {
  24909. return true;
  24910. }
  24911. else {
  24912. return false;
  24913. }
  24914. };
  24915. /**
  24916. * Use this method to simulate a pointer down on a mesh
  24917. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24918. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24919. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24920. * @returns the current scene
  24921. */
  24922. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24923. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24924. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  24925. return this;
  24926. }
  24927. return this._processPointerDown(pickResult, evt);
  24928. };
  24929. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24930. var _this = this;
  24931. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24932. this._pickedDownMesh = pickResult.pickedMesh;
  24933. var actionManager = pickResult.pickedMesh.actionManager;
  24934. if (actionManager) {
  24935. if (actionManager.hasPickTriggers) {
  24936. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24937. switch (evt.button) {
  24938. case 0:
  24939. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24940. break;
  24941. case 1:
  24942. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24943. break;
  24944. case 2:
  24945. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24946. break;
  24947. }
  24948. }
  24949. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24950. window.setTimeout(function () {
  24951. 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);
  24952. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24953. if (_this._totalPointersPressed !== 0 &&
  24954. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24955. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24956. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24957. _this._startingPointerTime = 0;
  24958. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24959. }
  24960. }
  24961. }, Scene.LongPressDelay);
  24962. }
  24963. }
  24964. }
  24965. if (pickResult) {
  24966. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24967. if (this.onPointerDown) {
  24968. this.onPointerDown(evt, pickResult, type);
  24969. }
  24970. if (this.onPointerObservable.hasObservers()) {
  24971. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24972. this._setRayOnPointerInfo(pi);
  24973. this.onPointerObservable.notifyObservers(pi, type);
  24974. }
  24975. }
  24976. return this;
  24977. };
  24978. /**
  24979. * Use this method to simulate a pointer up on a mesh
  24980. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24981. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24982. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24983. * @returns the current scene
  24984. */
  24985. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24986. var evt = new PointerEvent("pointerup", pointerEventInit);
  24987. var clickInfo = new ClickInfo();
  24988. clickInfo.singleClick = true;
  24989. clickInfo.ignore = true;
  24990. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  24991. return this;
  24992. }
  24993. return this._processPointerUp(pickResult, evt, clickInfo);
  24994. };
  24995. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24996. if (pickResult && pickResult && pickResult.pickedMesh) {
  24997. this._pickedUpMesh = pickResult.pickedMesh;
  24998. if (this._pickedDownMesh === this._pickedUpMesh) {
  24999. if (this.onPointerPick) {
  25000. this.onPointerPick(evt, pickResult);
  25001. }
  25002. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25003. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25004. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25005. this._setRayOnPointerInfo(pi);
  25006. this.onPointerObservable.notifyObservers(pi, type_1);
  25007. }
  25008. }
  25009. if (pickResult.pickedMesh.actionManager) {
  25010. if (clickInfo.ignore) {
  25011. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25012. }
  25013. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25014. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25015. }
  25016. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25017. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25018. }
  25019. }
  25020. }
  25021. if (this._pickedDownMesh &&
  25022. this._pickedDownMesh.actionManager &&
  25023. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25024. this._pickedDownMesh !== this._pickedUpMesh) {
  25025. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25026. }
  25027. var type = BABYLON.PointerEventTypes.POINTERUP;
  25028. if (this.onPointerObservable.hasObservers()) {
  25029. if (!clickInfo.ignore) {
  25030. if (!clickInfo.hasSwiped) {
  25031. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25032. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25033. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25034. this._setRayOnPointerInfo(pi);
  25035. this.onPointerObservable.notifyObservers(pi, type_2);
  25036. }
  25037. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25038. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25039. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25040. this._setRayOnPointerInfo(pi);
  25041. this.onPointerObservable.notifyObservers(pi, type_3);
  25042. }
  25043. }
  25044. }
  25045. else {
  25046. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25047. this._setRayOnPointerInfo(pi);
  25048. this.onPointerObservable.notifyObservers(pi, type);
  25049. }
  25050. }
  25051. if (this.onPointerUp) {
  25052. this.onPointerUp(evt, pickResult, type);
  25053. }
  25054. return this;
  25055. };
  25056. /**
  25057. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25058. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25059. * @returns true if the pointer was captured
  25060. */
  25061. Scene.prototype.isPointerCaptured = function (pointerId) {
  25062. if (pointerId === void 0) { pointerId = 0; }
  25063. return this._pointerCaptures[pointerId];
  25064. };
  25065. /**
  25066. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25067. * @param attachUp defines if you want to attach events to pointerup
  25068. * @param attachDown defines if you want to attach events to pointerdown
  25069. * @param attachMove defines if you want to attach events to pointermove
  25070. */
  25071. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25072. var _this = this;
  25073. if (attachUp === void 0) { attachUp = true; }
  25074. if (attachDown === void 0) { attachDown = true; }
  25075. if (attachMove === void 0) { attachMove = true; }
  25076. this._initActionManager = function (act, clickInfo) {
  25077. if (!_this._meshPickProceed) {
  25078. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25079. _this._currentPickResult = pickResult;
  25080. if (pickResult) {
  25081. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25082. }
  25083. _this._meshPickProceed = true;
  25084. }
  25085. return act;
  25086. };
  25087. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25088. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25089. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25090. btn !== _this._previousButtonPressed) {
  25091. _this._doubleClickOccured = false;
  25092. clickInfo.singleClick = true;
  25093. clickInfo.ignore = false;
  25094. cb(clickInfo, _this._currentPickResult);
  25095. }
  25096. };
  25097. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25098. var clickInfo = new ClickInfo();
  25099. _this._currentPickResult = null;
  25100. var act = null;
  25101. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25102. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25103. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25104. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25105. act = _this._initActionManager(act, clickInfo);
  25106. if (act)
  25107. checkPicking = act.hasPickTriggers;
  25108. }
  25109. if (checkPicking) {
  25110. var btn = evt.button;
  25111. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25112. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25113. if (!clickInfo.hasSwiped) {
  25114. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25115. if (!checkSingleClickImmediately) {
  25116. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25117. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25118. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25119. act = _this._initActionManager(act, clickInfo);
  25120. if (act)
  25121. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25122. }
  25123. }
  25124. if (checkSingleClickImmediately) {
  25125. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25126. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25127. btn !== _this._previousButtonPressed) {
  25128. clickInfo.singleClick = true;
  25129. cb(clickInfo, _this._currentPickResult);
  25130. }
  25131. }
  25132. // at least one double click is required to be check and exclusive double click is enabled
  25133. else {
  25134. // wait that no double click has been raised during the double click delay
  25135. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25136. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25137. }
  25138. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25139. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25140. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25141. act = _this._initActionManager(act, clickInfo);
  25142. if (act)
  25143. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25144. }
  25145. if (checkDoubleClick) {
  25146. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25147. if (btn === _this._previousButtonPressed &&
  25148. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25149. !_this._doubleClickOccured) {
  25150. // pointer has not moved for 2 clicks, it's a double click
  25151. if (!clickInfo.hasSwiped &&
  25152. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25153. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25154. _this._previousStartingPointerTime = 0;
  25155. _this._doubleClickOccured = true;
  25156. clickInfo.doubleClick = true;
  25157. clickInfo.ignore = false;
  25158. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25159. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25160. }
  25161. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25162. cb(clickInfo, _this._currentPickResult);
  25163. }
  25164. // if the two successive clicks are too far, it's just two simple clicks
  25165. else {
  25166. _this._doubleClickOccured = false;
  25167. _this._previousStartingPointerTime = _this._startingPointerTime;
  25168. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25169. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25170. _this._previousButtonPressed = btn;
  25171. if (Scene.ExclusiveDoubleClickMode) {
  25172. if (_this._previousDelayedSimpleClickTimeout) {
  25173. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25174. }
  25175. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25176. cb(clickInfo, _this._previousPickResult);
  25177. }
  25178. else {
  25179. cb(clickInfo, _this._currentPickResult);
  25180. }
  25181. }
  25182. }
  25183. // just the first click of the double has been raised
  25184. else {
  25185. _this._doubleClickOccured = false;
  25186. _this._previousStartingPointerTime = _this._startingPointerTime;
  25187. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25188. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25189. _this._previousButtonPressed = btn;
  25190. }
  25191. }
  25192. }
  25193. }
  25194. clickInfo.ignore = true;
  25195. cb(clickInfo, _this._currentPickResult);
  25196. };
  25197. this._spritePredicate = function (sprite) {
  25198. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25199. };
  25200. this._onPointerMove = function (evt) {
  25201. _this._updatePointerPosition(evt);
  25202. // PreObservable support
  25203. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25204. return;
  25205. }
  25206. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25207. return;
  25208. }
  25209. if (!_this.pointerMovePredicate) {
  25210. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25211. }
  25212. // Meshes
  25213. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25214. _this._processPointerMove(pickResult, evt);
  25215. };
  25216. this._onPointerDown = function (evt) {
  25217. _this._totalPointersPressed++;
  25218. _this._pickedDownMesh = null;
  25219. _this._meshPickProceed = false;
  25220. _this._updatePointerPosition(evt);
  25221. if (_this.preventDefaultOnPointerDown && canvas) {
  25222. evt.preventDefault();
  25223. canvas.focus();
  25224. }
  25225. // PreObservable support
  25226. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25227. return;
  25228. }
  25229. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25230. return;
  25231. }
  25232. _this._pointerCaptures[evt.pointerId] = true;
  25233. _this._startingPointerPosition.x = _this._pointerX;
  25234. _this._startingPointerPosition.y = _this._pointerY;
  25235. _this._startingPointerTime = Date.now();
  25236. if (!_this.pointerDownPredicate) {
  25237. _this.pointerDownPredicate = function (mesh) {
  25238. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25239. };
  25240. }
  25241. // Meshes
  25242. _this._pickedDownMesh = null;
  25243. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25244. _this._processPointerDown(pickResult, evt);
  25245. // Sprites
  25246. _this._pickedDownSprite = null;
  25247. if (_this.spriteManagers.length > 0) {
  25248. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25249. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25250. if (pickResult.pickedSprite.actionManager) {
  25251. _this._pickedDownSprite = pickResult.pickedSprite;
  25252. switch (evt.button) {
  25253. case 0:
  25254. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25255. break;
  25256. case 1:
  25257. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25258. break;
  25259. case 2:
  25260. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25261. break;
  25262. }
  25263. if (pickResult.pickedSprite.actionManager) {
  25264. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25265. }
  25266. }
  25267. }
  25268. }
  25269. };
  25270. this._onPointerUp = function (evt) {
  25271. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25272. return; // So we need to test it the pointer down was pressed before.
  25273. }
  25274. _this._totalPointersPressed--;
  25275. _this._pickedUpMesh = null;
  25276. _this._meshPickProceed = false;
  25277. _this._updatePointerPosition(evt);
  25278. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25279. // PreObservable support
  25280. if (_this.onPrePointerObservable.hasObservers()) {
  25281. if (!clickInfo.ignore) {
  25282. if (!clickInfo.hasSwiped) {
  25283. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25284. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25285. return;
  25286. }
  25287. }
  25288. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25289. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25290. return;
  25291. }
  25292. }
  25293. }
  25294. }
  25295. else {
  25296. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25297. return;
  25298. }
  25299. }
  25300. }
  25301. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25302. return;
  25303. }
  25304. _this._pointerCaptures[evt.pointerId] = false;
  25305. if (!_this.pointerUpPredicate) {
  25306. _this.pointerUpPredicate = function (mesh) {
  25307. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25308. };
  25309. }
  25310. // Meshes
  25311. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25312. _this._initActionManager(null, clickInfo);
  25313. }
  25314. if (!pickResult) {
  25315. pickResult = _this._currentPickResult;
  25316. }
  25317. _this._processPointerUp(pickResult, evt, clickInfo);
  25318. // Sprites
  25319. if (!clickInfo.ignore) {
  25320. if (_this.spriteManagers.length > 0) {
  25321. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25322. if (spritePickResult) {
  25323. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25324. if (spritePickResult.pickedSprite.actionManager) {
  25325. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25326. if (spritePickResult.pickedSprite.actionManager) {
  25327. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25328. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25329. }
  25330. }
  25331. }
  25332. }
  25333. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25334. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25335. }
  25336. }
  25337. }
  25338. }
  25339. _this._previousPickResult = _this._currentPickResult;
  25340. });
  25341. };
  25342. this._onKeyDown = function (evt) {
  25343. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25344. if (_this.onPreKeyboardObservable.hasObservers()) {
  25345. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25346. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25347. if (pi.skipOnPointerObservable) {
  25348. return;
  25349. }
  25350. }
  25351. if (_this.onKeyboardObservable.hasObservers()) {
  25352. var pi = new BABYLON.KeyboardInfo(type, evt);
  25353. _this.onKeyboardObservable.notifyObservers(pi, type);
  25354. }
  25355. if (_this.actionManager) {
  25356. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25357. }
  25358. };
  25359. this._onKeyUp = function (evt) {
  25360. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25361. if (_this.onPreKeyboardObservable.hasObservers()) {
  25362. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25363. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25364. if (pi.skipOnPointerObservable) {
  25365. return;
  25366. }
  25367. }
  25368. if (_this.onKeyboardObservable.hasObservers()) {
  25369. var pi = new BABYLON.KeyboardInfo(type, evt);
  25370. _this.onKeyboardObservable.notifyObservers(pi, type);
  25371. }
  25372. if (_this.actionManager) {
  25373. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25374. }
  25375. };
  25376. var engine = this.getEngine();
  25377. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25378. if (!canvas) {
  25379. return;
  25380. }
  25381. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25382. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25383. });
  25384. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25385. if (!canvas) {
  25386. return;
  25387. }
  25388. canvas.removeEventListener("keydown", _this._onKeyDown);
  25389. canvas.removeEventListener("keyup", _this._onKeyUp);
  25390. });
  25391. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25392. var canvas = this._engine.getRenderingCanvas();
  25393. if (!canvas) {
  25394. return;
  25395. }
  25396. if (attachMove) {
  25397. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25398. // Wheel
  25399. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25400. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25401. }
  25402. if (attachDown) {
  25403. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25404. }
  25405. if (attachUp) {
  25406. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25407. }
  25408. canvas.tabIndex = 1;
  25409. };
  25410. /** Detaches all event handlers*/
  25411. Scene.prototype.detachControl = function () {
  25412. var engine = this.getEngine();
  25413. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25414. var canvas = engine.getRenderingCanvas();
  25415. if (!canvas) {
  25416. return;
  25417. }
  25418. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25419. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25420. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25421. if (this._onCanvasBlurObserver) {
  25422. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25423. }
  25424. if (this._onCanvasFocusObserver) {
  25425. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25426. }
  25427. // Wheel
  25428. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25429. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25430. // Keyboard
  25431. canvas.removeEventListener("keydown", this._onKeyDown);
  25432. canvas.removeEventListener("keyup", this._onKeyUp);
  25433. // Observables
  25434. this.onKeyboardObservable.clear();
  25435. this.onPreKeyboardObservable.clear();
  25436. this.onPointerObservable.clear();
  25437. this.onPrePointerObservable.clear();
  25438. };
  25439. /**
  25440. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25441. * Delay loaded resources are not taking in account
  25442. * @return true if all required resources are ready
  25443. */
  25444. Scene.prototype.isReady = function () {
  25445. if (this._isDisposed) {
  25446. return false;
  25447. }
  25448. if (this._pendingData.length > 0) {
  25449. return false;
  25450. }
  25451. var index;
  25452. var engine = this.getEngine();
  25453. // Geometries
  25454. for (index = 0; index < this.geometries.length; index++) {
  25455. var geometry = this.geometries[index];
  25456. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25457. return false;
  25458. }
  25459. }
  25460. // Meshes
  25461. for (index = 0; index < this.meshes.length; index++) {
  25462. var mesh = this.meshes[index];
  25463. if (!mesh.isEnabled()) {
  25464. continue;
  25465. }
  25466. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25467. continue;
  25468. }
  25469. if (!mesh.isReady(true)) {
  25470. return false;
  25471. }
  25472. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25473. // Is Ready For Mesh
  25474. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25475. var step = _a[_i];
  25476. if (!step.action(mesh, hardwareInstancedRendering)) {
  25477. return false;
  25478. }
  25479. }
  25480. }
  25481. // Post-processes
  25482. if (this.activeCameras && this.activeCameras.length > 0) {
  25483. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25484. var camera = _c[_b];
  25485. if (!camera.isReady(true)) {
  25486. return false;
  25487. }
  25488. }
  25489. }
  25490. else if (this.activeCamera) {
  25491. if (!this.activeCamera.isReady(true)) {
  25492. return false;
  25493. }
  25494. }
  25495. // Particles
  25496. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25497. var particleSystem = _e[_d];
  25498. if (!particleSystem.isReady()) {
  25499. return false;
  25500. }
  25501. }
  25502. return true;
  25503. };
  25504. /** Resets all cached information relative to material (including effect and visibility) */
  25505. Scene.prototype.resetCachedMaterial = function () {
  25506. this._cachedMaterial = null;
  25507. this._cachedEffect = null;
  25508. this._cachedVisibility = null;
  25509. };
  25510. /**
  25511. * Registers a function to be called before every frame render
  25512. * @param func defines the function to register
  25513. */
  25514. Scene.prototype.registerBeforeRender = function (func) {
  25515. this.onBeforeRenderObservable.add(func);
  25516. };
  25517. /**
  25518. * Unregisters a function called before every frame render
  25519. * @param func defines the function to unregister
  25520. */
  25521. Scene.prototype.unregisterBeforeRender = function (func) {
  25522. this.onBeforeRenderObservable.removeCallback(func);
  25523. };
  25524. /**
  25525. * Registers a function to be called after every frame render
  25526. * @param func defines the function to register
  25527. */
  25528. Scene.prototype.registerAfterRender = function (func) {
  25529. this.onAfterRenderObservable.add(func);
  25530. };
  25531. /**
  25532. * Unregisters a function called after every frame render
  25533. * @param func defines the function to unregister
  25534. */
  25535. Scene.prototype.unregisterAfterRender = function (func) {
  25536. this.onAfterRenderObservable.removeCallback(func);
  25537. };
  25538. Scene.prototype._executeOnceBeforeRender = function (func) {
  25539. var _this = this;
  25540. var execFunc = function () {
  25541. func();
  25542. setTimeout(function () {
  25543. _this.unregisterBeforeRender(execFunc);
  25544. });
  25545. };
  25546. this.registerBeforeRender(execFunc);
  25547. };
  25548. /**
  25549. * The provided function will run before render once and will be disposed afterwards.
  25550. * A timeout delay can be provided so that the function will be executed in N ms.
  25551. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25552. * @param func The function to be executed.
  25553. * @param timeout optional delay in ms
  25554. */
  25555. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25556. var _this = this;
  25557. if (timeout !== undefined) {
  25558. setTimeout(function () {
  25559. _this._executeOnceBeforeRender(func);
  25560. }, timeout);
  25561. }
  25562. else {
  25563. this._executeOnceBeforeRender(func);
  25564. }
  25565. };
  25566. /** @hidden */
  25567. Scene.prototype._addPendingData = function (data) {
  25568. this._pendingData.push(data);
  25569. };
  25570. /** @hidden */
  25571. Scene.prototype._removePendingData = function (data) {
  25572. var wasLoading = this.isLoading;
  25573. var index = this._pendingData.indexOf(data);
  25574. if (index !== -1) {
  25575. this._pendingData.splice(index, 1);
  25576. }
  25577. if (wasLoading && !this.isLoading) {
  25578. this.onDataLoadedObservable.notifyObservers(this);
  25579. }
  25580. };
  25581. /**
  25582. * Returns the number of items waiting to be loaded
  25583. * @returns the number of items waiting to be loaded
  25584. */
  25585. Scene.prototype.getWaitingItemsCount = function () {
  25586. return this._pendingData.length;
  25587. };
  25588. Object.defineProperty(Scene.prototype, "isLoading", {
  25589. /**
  25590. * Returns a boolean indicating if the scene is still loading data
  25591. */
  25592. get: function () {
  25593. return this._pendingData.length > 0;
  25594. },
  25595. enumerable: true,
  25596. configurable: true
  25597. });
  25598. /**
  25599. * Registers a function to be executed when the scene is ready
  25600. * @param {Function} func - the function to be executed
  25601. */
  25602. Scene.prototype.executeWhenReady = function (func) {
  25603. var _this = this;
  25604. this.onReadyObservable.add(func);
  25605. if (this._executeWhenReadyTimeoutId !== -1) {
  25606. return;
  25607. }
  25608. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25609. _this._checkIsReady();
  25610. }, 150);
  25611. };
  25612. /**
  25613. * Returns a promise that resolves when the scene is ready
  25614. * @returns A promise that resolves when the scene is ready
  25615. */
  25616. Scene.prototype.whenReadyAsync = function () {
  25617. var _this = this;
  25618. return new Promise(function (resolve) {
  25619. _this.executeWhenReady(function () {
  25620. resolve();
  25621. });
  25622. });
  25623. };
  25624. /** @hidden */
  25625. Scene.prototype._checkIsReady = function () {
  25626. var _this = this;
  25627. this._registerTransientComponents();
  25628. if (this.isReady()) {
  25629. this.onReadyObservable.notifyObservers(this);
  25630. this.onReadyObservable.clear();
  25631. this._executeWhenReadyTimeoutId = -1;
  25632. return;
  25633. }
  25634. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25635. _this._checkIsReady();
  25636. }, 150);
  25637. };
  25638. // Animations
  25639. /**
  25640. * Will start the animation sequence of a given target
  25641. * @param target defines the target
  25642. * @param from defines from which frame should animation start
  25643. * @param to defines until which frame should animation run.
  25644. * @param weight defines the weight to apply to the animation (1.0 by default)
  25645. * @param loop defines if the animation loops
  25646. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25647. * @param onAnimationEnd defines the function to be executed when the animation ends
  25648. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25649. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25650. * @returns the animatable object created for this animation
  25651. */
  25652. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  25653. if (weight === void 0) { weight = 1.0; }
  25654. if (speedRatio === void 0) { speedRatio = 1.0; }
  25655. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  25656. returnedAnimatable.weight = weight;
  25657. return returnedAnimatable;
  25658. };
  25659. /**
  25660. * Will start the animation sequence of a given target
  25661. * @param target defines the target
  25662. * @param from defines from which frame should animation start
  25663. * @param to defines until which frame should animation run.
  25664. * @param loop defines if the animation loops
  25665. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25666. * @param onAnimationEnd defines the function to be executed when the animation ends
  25667. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25668. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25669. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  25670. * @returns the animatable object created for this animation
  25671. */
  25672. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  25673. if (speedRatio === void 0) { speedRatio = 1.0; }
  25674. if (stopCurrent === void 0) { stopCurrent = true; }
  25675. if (from > to && speedRatio > 0) {
  25676. speedRatio *= -1;
  25677. }
  25678. if (stopCurrent) {
  25679. this.stopAnimation(target, undefined, targetMask);
  25680. }
  25681. if (!animatable) {
  25682. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25683. }
  25684. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  25685. // Local animations
  25686. if (target.animations && shouldRunTargetAnimations) {
  25687. animatable.appendAnimations(target, target.animations);
  25688. }
  25689. // Children animations
  25690. if (target.getAnimatables) {
  25691. var animatables = target.getAnimatables();
  25692. for (var index = 0; index < animatables.length; index++) {
  25693. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  25694. }
  25695. }
  25696. animatable.reset();
  25697. return animatable;
  25698. };
  25699. /**
  25700. * Begin a new animation on a given node
  25701. * @param target defines the target where the animation will take place
  25702. * @param animations defines the list of animations to start
  25703. * @param from defines the initial value
  25704. * @param to defines the final value
  25705. * @param loop defines if you want animation to loop (off by default)
  25706. * @param speedRatio defines the speed ratio to apply to all animations
  25707. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25708. * @returns the list of created animatables
  25709. */
  25710. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25711. if (speedRatio === undefined) {
  25712. speedRatio = 1.0;
  25713. }
  25714. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25715. return animatable;
  25716. };
  25717. /**
  25718. * Begin a new animation on a given node and its hierarchy
  25719. * @param target defines the root node where the animation will take place
  25720. * @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.
  25721. * @param animations defines the list of animations to start
  25722. * @param from defines the initial value
  25723. * @param to defines the final value
  25724. * @param loop defines if you want animation to loop (off by default)
  25725. * @param speedRatio defines the speed ratio to apply to all animations
  25726. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25727. * @returns the list of animatables created for all nodes
  25728. */
  25729. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25730. var children = target.getDescendants(directDescendantsOnly);
  25731. var result = [];
  25732. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  25733. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25734. var child = children_1[_i];
  25735. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25736. }
  25737. return result;
  25738. };
  25739. /**
  25740. * Gets the animatable associated with a specific target
  25741. * @param target defines the target of the animatable
  25742. * @returns the required animatable if found
  25743. */
  25744. Scene.prototype.getAnimatableByTarget = function (target) {
  25745. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25746. if (this._activeAnimatables[index].target === target) {
  25747. return this._activeAnimatables[index];
  25748. }
  25749. }
  25750. return null;
  25751. };
  25752. /**
  25753. * Gets all animatables associated with a given target
  25754. * @param target defines the target to look animatables for
  25755. * @returns an array of Animatables
  25756. */
  25757. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25758. var result = [];
  25759. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25760. if (this._activeAnimatables[index].target === target) {
  25761. result.push(this._activeAnimatables[index]);
  25762. }
  25763. }
  25764. return result;
  25765. };
  25766. Object.defineProperty(Scene.prototype, "animatables", {
  25767. /**
  25768. * Gets all animatable attached to the scene
  25769. */
  25770. get: function () {
  25771. return this._activeAnimatables;
  25772. },
  25773. enumerable: true,
  25774. configurable: true
  25775. });
  25776. /**
  25777. * Will stop the animation of the given target
  25778. * @param target - the target
  25779. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  25780. * @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)
  25781. */
  25782. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  25783. var animatables = this.getAllAnimatablesByTarget(target);
  25784. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25785. var animatable = animatables_1[_i];
  25786. animatable.stop(animationName, targetMask);
  25787. }
  25788. };
  25789. /**
  25790. * Stops and removes all animations that have been applied to the scene
  25791. */
  25792. Scene.prototype.stopAllAnimations = function () {
  25793. if (this._activeAnimatables) {
  25794. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25795. this._activeAnimatables[i].stop();
  25796. }
  25797. this._activeAnimatables = [];
  25798. }
  25799. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25800. var group = _a[_i];
  25801. group.stop();
  25802. }
  25803. };
  25804. Scene.prototype._animate = function () {
  25805. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25806. return;
  25807. }
  25808. // Getting time
  25809. var now = BABYLON.Tools.Now;
  25810. if (!this._animationTimeLast) {
  25811. if (this._pendingData.length > 0) {
  25812. return;
  25813. }
  25814. this._animationTimeLast = now;
  25815. }
  25816. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25817. this._animationTime += deltaTime;
  25818. this._animationTimeLast = now;
  25819. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25820. this._activeAnimatables[index]._animate(this._animationTime);
  25821. }
  25822. // Late animation bindings
  25823. this._processLateAnimationBindings();
  25824. };
  25825. /** @hidden */
  25826. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25827. var target = runtimeAnimation.target;
  25828. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25829. if (!target._lateAnimationHolders) {
  25830. target._lateAnimationHolders = {};
  25831. }
  25832. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25833. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25834. totalWeight: 0,
  25835. animations: [],
  25836. originalValue: originalValue
  25837. };
  25838. }
  25839. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25840. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25841. };
  25842. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25843. var normalizer = 1.0;
  25844. var finalPosition = BABYLON.Tmp.Vector3[0];
  25845. var finalScaling = BABYLON.Tmp.Vector3[1];
  25846. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25847. var startIndex = 0;
  25848. var originalAnimation = holder.animations[0];
  25849. var originalValue = holder.originalValue;
  25850. var scale = 1;
  25851. if (holder.totalWeight < 1.0) {
  25852. // We need to mix the original value in
  25853. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25854. scale = 1.0 - holder.totalWeight;
  25855. }
  25856. else {
  25857. startIndex = 1;
  25858. // We need to normalize the weights
  25859. normalizer = holder.totalWeight;
  25860. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25861. scale = originalAnimation.weight / normalizer;
  25862. if (scale == 1) {
  25863. return originalAnimation.currentValue;
  25864. }
  25865. }
  25866. finalScaling.scaleInPlace(scale);
  25867. finalPosition.scaleInPlace(scale);
  25868. finalQuaternion.scaleInPlace(scale);
  25869. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25870. var runtimeAnimation = holder.animations[animIndex];
  25871. var scale = runtimeAnimation.weight / normalizer;
  25872. var currentPosition = BABYLON.Tmp.Vector3[2];
  25873. var currentScaling = BABYLON.Tmp.Vector3[3];
  25874. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25875. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25876. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25877. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25878. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25879. }
  25880. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25881. return originalAnimation._workValue;
  25882. };
  25883. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25884. var originalAnimation = holder.animations[0];
  25885. var originalValue = holder.originalValue;
  25886. if (holder.animations.length === 1) {
  25887. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25888. }
  25889. var normalizer = 1.0;
  25890. var quaternions;
  25891. var weights;
  25892. if (holder.totalWeight < 1.0) {
  25893. var scale = 1.0 - holder.totalWeight;
  25894. quaternions = [];
  25895. weights = [];
  25896. quaternions.push(originalValue);
  25897. weights.push(scale);
  25898. }
  25899. else {
  25900. if (holder.animations.length === 2) { // Slerp as soon as we can
  25901. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25902. }
  25903. quaternions = [];
  25904. weights = [];
  25905. normalizer = holder.totalWeight;
  25906. }
  25907. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25908. var runtimeAnimation = holder.animations[animIndex];
  25909. quaternions.push(runtimeAnimation.currentValue);
  25910. weights.push(runtimeAnimation.weight / normalizer);
  25911. }
  25912. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25913. var cumulativeAmount = 0;
  25914. var cumulativeQuaternion = null;
  25915. for (var index = 0; index < quaternions.length;) {
  25916. if (!cumulativeQuaternion) {
  25917. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25918. cumulativeAmount = weights[index] + weights[index + 1];
  25919. index += 2;
  25920. continue;
  25921. }
  25922. cumulativeAmount += weights[index];
  25923. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25924. index++;
  25925. }
  25926. return cumulativeQuaternion;
  25927. };
  25928. Scene.prototype._processLateAnimationBindings = function () {
  25929. if (!this._registeredForLateAnimationBindings.length) {
  25930. return;
  25931. }
  25932. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25933. var target = this._registeredForLateAnimationBindings.data[index];
  25934. for (var path in target._lateAnimationHolders) {
  25935. var holder = target._lateAnimationHolders[path];
  25936. var originalAnimation = holder.animations[0];
  25937. var originalValue = holder.originalValue;
  25938. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25939. var finalValue = void 0;
  25940. if (matrixDecomposeMode) {
  25941. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25942. }
  25943. else {
  25944. var quaternionMode = originalValue.w !== undefined;
  25945. if (quaternionMode) {
  25946. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25947. }
  25948. else {
  25949. var startIndex = 0;
  25950. var normalizer = 1.0;
  25951. if (holder.totalWeight < 1.0) {
  25952. // We need to mix the original value in
  25953. if (originalValue.scale) {
  25954. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25955. }
  25956. else {
  25957. finalValue = originalValue * (1.0 - holder.totalWeight);
  25958. }
  25959. }
  25960. else {
  25961. // We need to normalize the weights
  25962. normalizer = holder.totalWeight;
  25963. var scale_1 = originalAnimation.weight / normalizer;
  25964. if (scale_1 !== 1) {
  25965. if (originalAnimation.currentValue.scale) {
  25966. finalValue = originalAnimation.currentValue.scale(scale_1);
  25967. }
  25968. else {
  25969. finalValue = originalAnimation.currentValue * scale_1;
  25970. }
  25971. }
  25972. else {
  25973. finalValue = originalAnimation.currentValue;
  25974. }
  25975. startIndex = 1;
  25976. }
  25977. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25978. var runtimeAnimation = holder.animations[animIndex];
  25979. var scale = runtimeAnimation.weight / normalizer;
  25980. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25981. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25982. }
  25983. else {
  25984. finalValue += runtimeAnimation.currentValue * scale;
  25985. }
  25986. }
  25987. }
  25988. }
  25989. target[path] = finalValue;
  25990. }
  25991. target._lateAnimationHolders = {};
  25992. }
  25993. this._registeredForLateAnimationBindings.reset();
  25994. };
  25995. // Matrix
  25996. /** @hidden */
  25997. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25998. this._useAlternateCameraConfiguration = active;
  25999. };
  26000. /**
  26001. * Gets the current view matrix
  26002. * @returns a Matrix
  26003. */
  26004. Scene.prototype.getViewMatrix = function () {
  26005. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26006. };
  26007. /**
  26008. * Gets the current projection matrix
  26009. * @returns a Matrix
  26010. */
  26011. Scene.prototype.getProjectionMatrix = function () {
  26012. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26013. };
  26014. /**
  26015. * Gets the current transform matrix
  26016. * @returns a Matrix made of View * Projection
  26017. */
  26018. Scene.prototype.getTransformMatrix = function () {
  26019. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26020. };
  26021. /**
  26022. * Sets the current transform matrix
  26023. * @param view defines the View matrix to use
  26024. * @param projection defines the Projection matrix to use
  26025. */
  26026. Scene.prototype.setTransformMatrix = function (view, projection) {
  26027. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26028. return;
  26029. }
  26030. this._viewUpdateFlag = view.updateFlag;
  26031. this._projectionUpdateFlag = projection.updateFlag;
  26032. this._viewMatrix = view;
  26033. this._projectionMatrix = projection;
  26034. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26035. // Update frustum
  26036. if (!this._frustumPlanes) {
  26037. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26038. }
  26039. else {
  26040. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26041. }
  26042. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26043. var otherCamera = this.activeCamera._alternateCamera;
  26044. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26045. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26046. }
  26047. if (this._sceneUbo.useUbo) {
  26048. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26049. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26050. this._sceneUbo.update();
  26051. }
  26052. };
  26053. /** @hidden */
  26054. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26055. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26056. return;
  26057. }
  26058. this._alternateViewUpdateFlag = view.updateFlag;
  26059. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26060. this._alternateViewMatrix = view;
  26061. this._alternateProjectionMatrix = projection;
  26062. if (!this._alternateTransformMatrix) {
  26063. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26064. }
  26065. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26066. if (!this._alternateSceneUbo) {
  26067. this._createAlternateUbo();
  26068. }
  26069. if (this._alternateSceneUbo.useUbo) {
  26070. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26071. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26072. this._alternateSceneUbo.update();
  26073. }
  26074. };
  26075. /**
  26076. * Gets the uniform buffer used to store scene data
  26077. * @returns a UniformBuffer
  26078. */
  26079. Scene.prototype.getSceneUniformBuffer = function () {
  26080. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26081. };
  26082. /**
  26083. * Gets an unique (relatively to the current scene) Id
  26084. * @returns an unique number for the scene
  26085. */
  26086. Scene.prototype.getUniqueId = function () {
  26087. var result = Scene._uniqueIdCounter;
  26088. Scene._uniqueIdCounter++;
  26089. return result;
  26090. };
  26091. /**
  26092. * Add a mesh to the list of scene's meshes
  26093. * @param newMesh defines the mesh to add
  26094. * @param recursive if all child meshes should also be added to the scene
  26095. */
  26096. Scene.prototype.addMesh = function (newMesh, recursive) {
  26097. var _this = this;
  26098. if (recursive === void 0) { recursive = false; }
  26099. this.meshes.push(newMesh);
  26100. //notify the collision coordinator
  26101. if (this.collisionCoordinator) {
  26102. this.collisionCoordinator.onMeshAdded(newMesh);
  26103. }
  26104. newMesh._resyncLightSources();
  26105. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26106. if (recursive) {
  26107. newMesh.getChildMeshes().forEach(function (m) {
  26108. _this.addMesh(m);
  26109. });
  26110. }
  26111. };
  26112. /**
  26113. * Remove a mesh for the list of scene's meshes
  26114. * @param toRemove defines the mesh to remove
  26115. * @param recursive if all child meshes should also be removed from the scene
  26116. * @returns the index where the mesh was in the mesh list
  26117. */
  26118. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26119. var _this = this;
  26120. if (recursive === void 0) { recursive = false; }
  26121. var index = this.meshes.indexOf(toRemove);
  26122. if (index !== -1) {
  26123. // Remove from the scene if mesh found
  26124. this.meshes.splice(index, 1);
  26125. }
  26126. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26127. if (recursive) {
  26128. toRemove.getChildMeshes().forEach(function (m) {
  26129. _this.removeMesh(m);
  26130. });
  26131. }
  26132. return index;
  26133. };
  26134. /**
  26135. * Add a transform node to the list of scene's transform nodes
  26136. * @param newTransformNode defines the transform node to add
  26137. */
  26138. Scene.prototype.addTransformNode = function (newTransformNode) {
  26139. this.transformNodes.push(newTransformNode);
  26140. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26141. };
  26142. /**
  26143. * Remove a transform node for the list of scene's transform nodes
  26144. * @param toRemove defines the transform node to remove
  26145. * @returns the index where the transform node was in the transform node list
  26146. */
  26147. Scene.prototype.removeTransformNode = function (toRemove) {
  26148. var index = this.transformNodes.indexOf(toRemove);
  26149. if (index !== -1) {
  26150. // Remove from the scene if found
  26151. this.transformNodes.splice(index, 1);
  26152. }
  26153. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26154. return index;
  26155. };
  26156. /**
  26157. * Remove a skeleton for the list of scene's skeletons
  26158. * @param toRemove defines the skeleton to remove
  26159. * @returns the index where the skeleton was in the skeleton list
  26160. */
  26161. Scene.prototype.removeSkeleton = function (toRemove) {
  26162. var index = this.skeletons.indexOf(toRemove);
  26163. if (index !== -1) {
  26164. // Remove from the scene if found
  26165. this.skeletons.splice(index, 1);
  26166. }
  26167. return index;
  26168. };
  26169. /**
  26170. * Remove a morph target for the list of scene's morph targets
  26171. * @param toRemove defines the morph target to remove
  26172. * @returns the index where the morph target was in the morph target list
  26173. */
  26174. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26175. var index = this.morphTargetManagers.indexOf(toRemove);
  26176. if (index !== -1) {
  26177. // Remove from the scene if found
  26178. this.morphTargetManagers.splice(index, 1);
  26179. }
  26180. return index;
  26181. };
  26182. /**
  26183. * Remove a light for the list of scene's lights
  26184. * @param toRemove defines the light to remove
  26185. * @returns the index where the light was in the light list
  26186. */
  26187. Scene.prototype.removeLight = function (toRemove) {
  26188. var index = this.lights.indexOf(toRemove);
  26189. if (index !== -1) {
  26190. // Remove from meshes
  26191. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26192. var mesh = _a[_i];
  26193. mesh._removeLightSource(toRemove);
  26194. }
  26195. // Remove from the scene if mesh found
  26196. this.lights.splice(index, 1);
  26197. this.sortLightsByPriority();
  26198. }
  26199. this.onLightRemovedObservable.notifyObservers(toRemove);
  26200. return index;
  26201. };
  26202. /**
  26203. * Remove a camera for the list of scene's cameras
  26204. * @param toRemove defines the camera to remove
  26205. * @returns the index where the camera was in the camera list
  26206. */
  26207. Scene.prototype.removeCamera = function (toRemove) {
  26208. var index = this.cameras.indexOf(toRemove);
  26209. if (index !== -1) {
  26210. // Remove from the scene if mesh found
  26211. this.cameras.splice(index, 1);
  26212. }
  26213. // Remove from activeCameras
  26214. var index2 = this.activeCameras.indexOf(toRemove);
  26215. if (index2 !== -1) {
  26216. // Remove from the scene if mesh found
  26217. this.activeCameras.splice(index2, 1);
  26218. }
  26219. // Reset the activeCamera
  26220. if (this.activeCamera === toRemove) {
  26221. if (this.cameras.length > 0) {
  26222. this.activeCamera = this.cameras[0];
  26223. }
  26224. else {
  26225. this.activeCamera = null;
  26226. }
  26227. }
  26228. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26229. return index;
  26230. };
  26231. /**
  26232. * Remove a particle system for the list of scene's particle systems
  26233. * @param toRemove defines the particle system to remove
  26234. * @returns the index where the particle system was in the particle system list
  26235. */
  26236. Scene.prototype.removeParticleSystem = function (toRemove) {
  26237. var index = this.particleSystems.indexOf(toRemove);
  26238. if (index !== -1) {
  26239. this.particleSystems.splice(index, 1);
  26240. }
  26241. return index;
  26242. };
  26243. /**
  26244. * Remove a animation for the list of scene's animations
  26245. * @param toRemove defines the animation to remove
  26246. * @returns the index where the animation was in the animation list
  26247. */
  26248. Scene.prototype.removeAnimation = function (toRemove) {
  26249. var index = this.animations.indexOf(toRemove);
  26250. if (index !== -1) {
  26251. this.animations.splice(index, 1);
  26252. }
  26253. return index;
  26254. };
  26255. /**
  26256. * Removes the given animation group from this scene.
  26257. * @param toRemove The animation group to remove
  26258. * @returns The index of the removed animation group
  26259. */
  26260. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26261. var index = this.animationGroups.indexOf(toRemove);
  26262. if (index !== -1) {
  26263. this.animationGroups.splice(index, 1);
  26264. }
  26265. return index;
  26266. };
  26267. /**
  26268. * Removes the given multi-material from this scene.
  26269. * @param toRemove The multi-material to remove
  26270. * @returns The index of the removed multi-material
  26271. */
  26272. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26273. var index = this.multiMaterials.indexOf(toRemove);
  26274. if (index !== -1) {
  26275. this.multiMaterials.splice(index, 1);
  26276. }
  26277. return index;
  26278. };
  26279. /**
  26280. * Removes the given material from this scene.
  26281. * @param toRemove The material to remove
  26282. * @returns The index of the removed material
  26283. */
  26284. Scene.prototype.removeMaterial = function (toRemove) {
  26285. var index = this.materials.indexOf(toRemove);
  26286. if (index !== -1) {
  26287. this.materials.splice(index, 1);
  26288. }
  26289. return index;
  26290. };
  26291. /**
  26292. * Removes the given action manager from this scene.
  26293. * @param toRemove The action manager to remove
  26294. * @returns The index of the removed action manager
  26295. */
  26296. Scene.prototype.removeActionManager = function (toRemove) {
  26297. var index = this.actionManagers.indexOf(toRemove);
  26298. if (index !== -1) {
  26299. this.actionManagers.splice(index, 1);
  26300. }
  26301. return index;
  26302. };
  26303. /**
  26304. * Removes the given texture from this scene.
  26305. * @param toRemove The texture to remove
  26306. * @returns The index of the removed texture
  26307. */
  26308. Scene.prototype.removeTexture = function (toRemove) {
  26309. var index = this.textures.indexOf(toRemove);
  26310. if (index !== -1) {
  26311. this.textures.splice(index, 1);
  26312. }
  26313. return index;
  26314. };
  26315. /**
  26316. * Adds the given light to this scene
  26317. * @param newLight The light to add
  26318. */
  26319. Scene.prototype.addLight = function (newLight) {
  26320. this.lights.push(newLight);
  26321. this.sortLightsByPriority();
  26322. // Add light to all meshes (To support if the light is removed and then readded)
  26323. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26324. var mesh = _a[_i];
  26325. if (mesh._lightSources.indexOf(newLight) === -1) {
  26326. mesh._lightSources.push(newLight);
  26327. mesh._resyncLightSources();
  26328. }
  26329. }
  26330. this.onNewLightAddedObservable.notifyObservers(newLight);
  26331. };
  26332. /**
  26333. * Sorts the list list based on light priorities
  26334. */
  26335. Scene.prototype.sortLightsByPriority = function () {
  26336. if (this.requireLightSorting) {
  26337. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26338. }
  26339. };
  26340. /**
  26341. * Adds the given camera to this scene
  26342. * @param newCamera The camera to add
  26343. */
  26344. Scene.prototype.addCamera = function (newCamera) {
  26345. this.cameras.push(newCamera);
  26346. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26347. };
  26348. /**
  26349. * Adds the given skeleton to this scene
  26350. * @param newSkeleton The skeleton to add
  26351. */
  26352. Scene.prototype.addSkeleton = function (newSkeleton) {
  26353. this.skeletons.push(newSkeleton);
  26354. };
  26355. /**
  26356. * Adds the given particle system to this scene
  26357. * @param newParticleSystem The particle system to add
  26358. */
  26359. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26360. this.particleSystems.push(newParticleSystem);
  26361. };
  26362. /**
  26363. * Adds the given animation to this scene
  26364. * @param newAnimation The animation to add
  26365. */
  26366. Scene.prototype.addAnimation = function (newAnimation) {
  26367. this.animations.push(newAnimation);
  26368. };
  26369. /**
  26370. * Adds the given animation group to this scene.
  26371. * @param newAnimationGroup The animation group to add
  26372. */
  26373. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26374. this.animationGroups.push(newAnimationGroup);
  26375. };
  26376. /**
  26377. * Adds the given multi-material to this scene
  26378. * @param newMultiMaterial The multi-material to add
  26379. */
  26380. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26381. this.multiMaterials.push(newMultiMaterial);
  26382. };
  26383. /**
  26384. * Adds the given material to this scene
  26385. * @param newMaterial The material to add
  26386. */
  26387. Scene.prototype.addMaterial = function (newMaterial) {
  26388. this.materials.push(newMaterial);
  26389. };
  26390. /**
  26391. * Adds the given morph target to this scene
  26392. * @param newMorphTargetManager The morph target to add
  26393. */
  26394. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26395. this.morphTargetManagers.push(newMorphTargetManager);
  26396. };
  26397. /**
  26398. * Adds the given geometry to this scene
  26399. * @param newGeometry The geometry to add
  26400. */
  26401. Scene.prototype.addGeometry = function (newGeometry) {
  26402. this.geometries.push(newGeometry);
  26403. };
  26404. /**
  26405. * Adds the given action manager to this scene
  26406. * @param newActionManager The action manager to add
  26407. */
  26408. Scene.prototype.addActionManager = function (newActionManager) {
  26409. this.actionManagers.push(newActionManager);
  26410. };
  26411. /**
  26412. * Adds the given texture to this scene.
  26413. * @param newTexture The texture to add
  26414. */
  26415. Scene.prototype.addTexture = function (newTexture) {
  26416. this.textures.push(newTexture);
  26417. };
  26418. /**
  26419. * Switch active camera
  26420. * @param newCamera defines the new active camera
  26421. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26422. */
  26423. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26424. if (attachControl === void 0) { attachControl = true; }
  26425. var canvas = this._engine.getRenderingCanvas();
  26426. if (!canvas) {
  26427. return;
  26428. }
  26429. if (this.activeCamera) {
  26430. this.activeCamera.detachControl(canvas);
  26431. }
  26432. this.activeCamera = newCamera;
  26433. if (attachControl) {
  26434. newCamera.attachControl(canvas);
  26435. }
  26436. };
  26437. /**
  26438. * sets the active camera of the scene using its ID
  26439. * @param id defines the camera's ID
  26440. * @return the new active camera or null if none found.
  26441. */
  26442. Scene.prototype.setActiveCameraByID = function (id) {
  26443. var camera = this.getCameraByID(id);
  26444. if (camera) {
  26445. this.activeCamera = camera;
  26446. return camera;
  26447. }
  26448. return null;
  26449. };
  26450. /**
  26451. * sets the active camera of the scene using its name
  26452. * @param name defines the camera's name
  26453. * @returns the new active camera or null if none found.
  26454. */
  26455. Scene.prototype.setActiveCameraByName = function (name) {
  26456. var camera = this.getCameraByName(name);
  26457. if (camera) {
  26458. this.activeCamera = camera;
  26459. return camera;
  26460. }
  26461. return null;
  26462. };
  26463. /**
  26464. * get an animation group using its name
  26465. * @param name defines the material's name
  26466. * @return the animation group or null if none found.
  26467. */
  26468. Scene.prototype.getAnimationGroupByName = function (name) {
  26469. for (var index = 0; index < this.animationGroups.length; index++) {
  26470. if (this.animationGroups[index].name === name) {
  26471. return this.animationGroups[index];
  26472. }
  26473. }
  26474. return null;
  26475. };
  26476. /**
  26477. * get a material using its id
  26478. * @param id defines the material's ID
  26479. * @return the material or null if none found.
  26480. */
  26481. Scene.prototype.getMaterialByID = function (id) {
  26482. for (var index = 0; index < this.materials.length; index++) {
  26483. if (this.materials[index].id === id) {
  26484. return this.materials[index];
  26485. }
  26486. }
  26487. return null;
  26488. };
  26489. /**
  26490. * Gets a material using its name
  26491. * @param name defines the material's name
  26492. * @return the material or null if none found.
  26493. */
  26494. Scene.prototype.getMaterialByName = function (name) {
  26495. for (var index = 0; index < this.materials.length; index++) {
  26496. if (this.materials[index].name === name) {
  26497. return this.materials[index];
  26498. }
  26499. }
  26500. return null;
  26501. };
  26502. /**
  26503. * Gets a camera using its id
  26504. * @param id defines the id to look for
  26505. * @returns the camera or null if not found
  26506. */
  26507. Scene.prototype.getCameraByID = function (id) {
  26508. for (var index = 0; index < this.cameras.length; index++) {
  26509. if (this.cameras[index].id === id) {
  26510. return this.cameras[index];
  26511. }
  26512. }
  26513. return null;
  26514. };
  26515. /**
  26516. * Gets a camera using its unique id
  26517. * @param uniqueId defines the unique id to look for
  26518. * @returns the camera or null if not found
  26519. */
  26520. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26521. for (var index = 0; index < this.cameras.length; index++) {
  26522. if (this.cameras[index].uniqueId === uniqueId) {
  26523. return this.cameras[index];
  26524. }
  26525. }
  26526. return null;
  26527. };
  26528. /**
  26529. * Gets a camera using its name
  26530. * @param name defines the camera's name
  26531. * @return the camera or null if none found.
  26532. */
  26533. Scene.prototype.getCameraByName = function (name) {
  26534. for (var index = 0; index < this.cameras.length; index++) {
  26535. if (this.cameras[index].name === name) {
  26536. return this.cameras[index];
  26537. }
  26538. }
  26539. return null;
  26540. };
  26541. /**
  26542. * Gets a bone using its id
  26543. * @param id defines the bone's id
  26544. * @return the bone or null if not found
  26545. */
  26546. Scene.prototype.getBoneByID = function (id) {
  26547. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26548. var skeleton = this.skeletons[skeletonIndex];
  26549. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26550. if (skeleton.bones[boneIndex].id === id) {
  26551. return skeleton.bones[boneIndex];
  26552. }
  26553. }
  26554. }
  26555. return null;
  26556. };
  26557. /**
  26558. * Gets a bone using its id
  26559. * @param name defines the bone's name
  26560. * @return the bone or null if not found
  26561. */
  26562. Scene.prototype.getBoneByName = function (name) {
  26563. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26564. var skeleton = this.skeletons[skeletonIndex];
  26565. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26566. if (skeleton.bones[boneIndex].name === name) {
  26567. return skeleton.bones[boneIndex];
  26568. }
  26569. }
  26570. }
  26571. return null;
  26572. };
  26573. /**
  26574. * Gets a light node using its name
  26575. * @param name defines the the light's name
  26576. * @return the light or null if none found.
  26577. */
  26578. Scene.prototype.getLightByName = function (name) {
  26579. for (var index = 0; index < this.lights.length; index++) {
  26580. if (this.lights[index].name === name) {
  26581. return this.lights[index];
  26582. }
  26583. }
  26584. return null;
  26585. };
  26586. /**
  26587. * Gets a light node using its id
  26588. * @param id defines the light's id
  26589. * @return the light or null if none found.
  26590. */
  26591. Scene.prototype.getLightByID = function (id) {
  26592. for (var index = 0; index < this.lights.length; index++) {
  26593. if (this.lights[index].id === id) {
  26594. return this.lights[index];
  26595. }
  26596. }
  26597. return null;
  26598. };
  26599. /**
  26600. * Gets a light node using its scene-generated unique ID
  26601. * @param uniqueId defines the light's unique id
  26602. * @return the light or null if none found.
  26603. */
  26604. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26605. for (var index = 0; index < this.lights.length; index++) {
  26606. if (this.lights[index].uniqueId === uniqueId) {
  26607. return this.lights[index];
  26608. }
  26609. }
  26610. return null;
  26611. };
  26612. /**
  26613. * Gets a particle system by id
  26614. * @param id defines the particle system id
  26615. * @return the corresponding system or null if none found
  26616. */
  26617. Scene.prototype.getParticleSystemByID = function (id) {
  26618. for (var index = 0; index < this.particleSystems.length; index++) {
  26619. if (this.particleSystems[index].id === id) {
  26620. return this.particleSystems[index];
  26621. }
  26622. }
  26623. return null;
  26624. };
  26625. /**
  26626. * Gets a geometry using its ID
  26627. * @param id defines the geometry's id
  26628. * @return the geometry or null if none found.
  26629. */
  26630. Scene.prototype.getGeometryByID = function (id) {
  26631. for (var index = 0; index < this.geometries.length; index++) {
  26632. if (this.geometries[index].id === id) {
  26633. return this.geometries[index];
  26634. }
  26635. }
  26636. return null;
  26637. };
  26638. /**
  26639. * Add a new geometry to this scene
  26640. * @param geometry defines the geometry to be added to the scene.
  26641. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26642. * @return a boolean defining if the geometry was added or not
  26643. */
  26644. Scene.prototype.pushGeometry = function (geometry, force) {
  26645. if (!force && this.getGeometryByID(geometry.id)) {
  26646. return false;
  26647. }
  26648. this.geometries.push(geometry);
  26649. //notify the collision coordinator
  26650. if (this.collisionCoordinator) {
  26651. this.collisionCoordinator.onGeometryAdded(geometry);
  26652. }
  26653. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26654. return true;
  26655. };
  26656. /**
  26657. * Removes an existing geometry
  26658. * @param geometry defines the geometry to be removed from the scene
  26659. * @return a boolean defining if the geometry was removed or not
  26660. */
  26661. Scene.prototype.removeGeometry = function (geometry) {
  26662. var index = this.geometries.indexOf(geometry);
  26663. if (index > -1) {
  26664. this.geometries.splice(index, 1);
  26665. //notify the collision coordinator
  26666. if (this.collisionCoordinator) {
  26667. this.collisionCoordinator.onGeometryDeleted(geometry);
  26668. }
  26669. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26670. return true;
  26671. }
  26672. return false;
  26673. };
  26674. /**
  26675. * Gets the list of geometries attached to the scene
  26676. * @returns an array of Geometry
  26677. */
  26678. Scene.prototype.getGeometries = function () {
  26679. return this.geometries;
  26680. };
  26681. /**
  26682. * Gets the first added mesh found of a given ID
  26683. * @param id defines the id to search for
  26684. * @return the mesh found or null if not found at all
  26685. */
  26686. Scene.prototype.getMeshByID = function (id) {
  26687. for (var index = 0; index < this.meshes.length; index++) {
  26688. if (this.meshes[index].id === id) {
  26689. return this.meshes[index];
  26690. }
  26691. }
  26692. return null;
  26693. };
  26694. /**
  26695. * Gets a list of meshes using their id
  26696. * @param id defines the id to search for
  26697. * @returns a list of meshes
  26698. */
  26699. Scene.prototype.getMeshesByID = function (id) {
  26700. return this.meshes.filter(function (m) {
  26701. return m.id === id;
  26702. });
  26703. };
  26704. /**
  26705. * Gets the first added transform node found of a given ID
  26706. * @param id defines the id to search for
  26707. * @return the found transform node or null if not found at all.
  26708. */
  26709. Scene.prototype.getTransformNodeByID = function (id) {
  26710. for (var index = 0; index < this.transformNodes.length; index++) {
  26711. if (this.transformNodes[index].id === id) {
  26712. return this.transformNodes[index];
  26713. }
  26714. }
  26715. return null;
  26716. };
  26717. /**
  26718. * Gets a list of transform nodes using their id
  26719. * @param id defines the id to search for
  26720. * @returns a list of transform nodes
  26721. */
  26722. Scene.prototype.getTransformNodesByID = function (id) {
  26723. return this.transformNodes.filter(function (m) {
  26724. return m.id === id;
  26725. });
  26726. };
  26727. /**
  26728. * Gets a mesh with its auto-generated unique id
  26729. * @param uniqueId defines the unique id to search for
  26730. * @return the found mesh or null if not found at all.
  26731. */
  26732. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26733. for (var index = 0; index < this.meshes.length; index++) {
  26734. if (this.meshes[index].uniqueId === uniqueId) {
  26735. return this.meshes[index];
  26736. }
  26737. }
  26738. return null;
  26739. };
  26740. /**
  26741. * Gets a the last added mesh using a given id
  26742. * @param id defines the id to search for
  26743. * @return the found mesh or null if not found at all.
  26744. */
  26745. Scene.prototype.getLastMeshByID = function (id) {
  26746. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26747. if (this.meshes[index].id === id) {
  26748. return this.meshes[index];
  26749. }
  26750. }
  26751. return null;
  26752. };
  26753. /**
  26754. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26755. * @param id defines the id to search for
  26756. * @return the found node or null if not found at all
  26757. */
  26758. Scene.prototype.getLastEntryByID = function (id) {
  26759. var index;
  26760. for (index = this.meshes.length - 1; index >= 0; index--) {
  26761. if (this.meshes[index].id === id) {
  26762. return this.meshes[index];
  26763. }
  26764. }
  26765. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26766. if (this.transformNodes[index].id === id) {
  26767. return this.transformNodes[index];
  26768. }
  26769. }
  26770. for (index = this.cameras.length - 1; index >= 0; index--) {
  26771. if (this.cameras[index].id === id) {
  26772. return this.cameras[index];
  26773. }
  26774. }
  26775. for (index = this.lights.length - 1; index >= 0; index--) {
  26776. if (this.lights[index].id === id) {
  26777. return this.lights[index];
  26778. }
  26779. }
  26780. return null;
  26781. };
  26782. /**
  26783. * Gets a node (Mesh, Camera, Light) using a given id
  26784. * @param id defines the id to search for
  26785. * @return the found node or null if not found at all
  26786. */
  26787. Scene.prototype.getNodeByID = function (id) {
  26788. var mesh = this.getMeshByID(id);
  26789. if (mesh) {
  26790. return mesh;
  26791. }
  26792. var light = this.getLightByID(id);
  26793. if (light) {
  26794. return light;
  26795. }
  26796. var camera = this.getCameraByID(id);
  26797. if (camera) {
  26798. return camera;
  26799. }
  26800. var bone = this.getBoneByID(id);
  26801. return bone;
  26802. };
  26803. /**
  26804. * Gets a node (Mesh, Camera, Light) using a given name
  26805. * @param name defines the name to search for
  26806. * @return the found node or null if not found at all.
  26807. */
  26808. Scene.prototype.getNodeByName = function (name) {
  26809. var mesh = this.getMeshByName(name);
  26810. if (mesh) {
  26811. return mesh;
  26812. }
  26813. var light = this.getLightByName(name);
  26814. if (light) {
  26815. return light;
  26816. }
  26817. var camera = this.getCameraByName(name);
  26818. if (camera) {
  26819. return camera;
  26820. }
  26821. var bone = this.getBoneByName(name);
  26822. return bone;
  26823. };
  26824. /**
  26825. * Gets a mesh using a given name
  26826. * @param name defines the name to search for
  26827. * @return the found mesh or null if not found at all.
  26828. */
  26829. Scene.prototype.getMeshByName = function (name) {
  26830. for (var index = 0; index < this.meshes.length; index++) {
  26831. if (this.meshes[index].name === name) {
  26832. return this.meshes[index];
  26833. }
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * Gets a transform node using a given name
  26839. * @param name defines the name to search for
  26840. * @return the found transform node or null if not found at all.
  26841. */
  26842. Scene.prototype.getTransformNodeByName = function (name) {
  26843. for (var index = 0; index < this.transformNodes.length; index++) {
  26844. if (this.transformNodes[index].name === name) {
  26845. return this.transformNodes[index];
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * Gets a sound using a given name
  26852. * @param name defines the name to search for
  26853. * @return the found sound or null if not found at all.
  26854. */
  26855. Scene.prototype.getSoundByName = function (name) {
  26856. var index;
  26857. if (BABYLON.AudioEngine) {
  26858. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26859. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26860. return this.mainSoundTrack.soundCollection[index];
  26861. }
  26862. }
  26863. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26864. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26865. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26866. return this.soundTracks[sdIndex].soundCollection[index];
  26867. }
  26868. }
  26869. }
  26870. }
  26871. return null;
  26872. };
  26873. /**
  26874. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26875. * @param id defines the id to search for
  26876. * @return the found skeleton or null if not found at all.
  26877. */
  26878. Scene.prototype.getLastSkeletonByID = function (id) {
  26879. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26880. if (this.skeletons[index].id === id) {
  26881. return this.skeletons[index];
  26882. }
  26883. }
  26884. return null;
  26885. };
  26886. /**
  26887. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26888. * @param id defines the id to search for
  26889. * @return the found skeleton or null if not found at all.
  26890. */
  26891. Scene.prototype.getSkeletonById = function (id) {
  26892. for (var index = 0; index < this.skeletons.length; index++) {
  26893. if (this.skeletons[index].id === id) {
  26894. return this.skeletons[index];
  26895. }
  26896. }
  26897. return null;
  26898. };
  26899. /**
  26900. * Gets a skeleton using a given name
  26901. * @param name defines the name to search for
  26902. * @return the found skeleton or null if not found at all.
  26903. */
  26904. Scene.prototype.getSkeletonByName = function (name) {
  26905. for (var index = 0; index < this.skeletons.length; index++) {
  26906. if (this.skeletons[index].name === name) {
  26907. return this.skeletons[index];
  26908. }
  26909. }
  26910. return null;
  26911. };
  26912. /**
  26913. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26914. * @param id defines the id to search for
  26915. * @return the found morph target manager or null if not found at all.
  26916. */
  26917. Scene.prototype.getMorphTargetManagerById = function (id) {
  26918. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26919. if (this.morphTargetManagers[index].uniqueId === id) {
  26920. return this.morphTargetManagers[index];
  26921. }
  26922. }
  26923. return null;
  26924. };
  26925. /**
  26926. * Gets a boolean indicating if the given mesh is active
  26927. * @param mesh defines the mesh to look for
  26928. * @returns true if the mesh is in the active list
  26929. */
  26930. Scene.prototype.isActiveMesh = function (mesh) {
  26931. return (this._activeMeshes.indexOf(mesh) !== -1);
  26932. };
  26933. Object.defineProperty(Scene.prototype, "uid", {
  26934. /**
  26935. * Return a unique id as a string which can serve as an identifier for the scene
  26936. */
  26937. get: function () {
  26938. if (!this._uid) {
  26939. this._uid = BABYLON.Tools.RandomId();
  26940. }
  26941. return this._uid;
  26942. },
  26943. enumerable: true,
  26944. configurable: true
  26945. });
  26946. /**
  26947. * Add an externaly attached data from its key.
  26948. * This method call will fail and return false, if such key already exists.
  26949. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26950. * @param key the unique key that identifies the data
  26951. * @param data the data object to associate to the key for this Engine instance
  26952. * @return true if no such key were already present and the data was added successfully, false otherwise
  26953. */
  26954. Scene.prototype.addExternalData = function (key, data) {
  26955. if (!this._externalData) {
  26956. this._externalData = new BABYLON.StringDictionary();
  26957. }
  26958. return this._externalData.add(key, data);
  26959. };
  26960. /**
  26961. * Get an externaly attached data from its key
  26962. * @param key the unique key that identifies the data
  26963. * @return the associated data, if present (can be null), or undefined if not present
  26964. */
  26965. Scene.prototype.getExternalData = function (key) {
  26966. if (!this._externalData) {
  26967. return null;
  26968. }
  26969. return this._externalData.get(key);
  26970. };
  26971. /**
  26972. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26973. * @param key the unique key that identifies the data
  26974. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26975. * @return the associated data, can be null if the factory returned null.
  26976. */
  26977. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26978. if (!this._externalData) {
  26979. this._externalData = new BABYLON.StringDictionary();
  26980. }
  26981. return this._externalData.getOrAddWithFactory(key, factory);
  26982. };
  26983. /**
  26984. * Remove an externaly attached data from the Engine instance
  26985. * @param key the unique key that identifies the data
  26986. * @return true if the data was successfully removed, false if it doesn't exist
  26987. */
  26988. Scene.prototype.removeExternalData = function (key) {
  26989. return this._externalData.remove(key);
  26990. };
  26991. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26992. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26993. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  26994. var step = _a[_i];
  26995. step.action(mesh, subMesh);
  26996. }
  26997. var material = subMesh.getMaterial();
  26998. if (material !== null && material !== undefined) {
  26999. // Render targets
  27000. if (material.getRenderTargetTextures !== undefined) {
  27001. if (this._processedMaterials.indexOf(material) === -1) {
  27002. this._processedMaterials.push(material);
  27003. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27004. }
  27005. }
  27006. // Dispatch
  27007. this._activeIndices.addCount(subMesh.indexCount, false);
  27008. this._renderingManager.dispatch(subMesh, mesh, material);
  27009. }
  27010. }
  27011. };
  27012. /**
  27013. * Clear the processed materials smart array preventing retention point in material dispose.
  27014. */
  27015. Scene.prototype.freeProcessedMaterials = function () {
  27016. this._processedMaterials.dispose();
  27017. };
  27018. /**
  27019. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27020. */
  27021. Scene.prototype.freeActiveMeshes = function () {
  27022. this._activeMeshes.dispose();
  27023. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27024. this.activeCamera._activeMeshes.dispose();
  27025. }
  27026. if (this.activeCameras) {
  27027. for (var i = 0; i < this.activeCameras.length; i++) {
  27028. var activeCamera = this.activeCameras[i];
  27029. if (activeCamera && activeCamera._activeMeshes) {
  27030. activeCamera._activeMeshes.dispose();
  27031. }
  27032. }
  27033. }
  27034. };
  27035. /**
  27036. * Clear the info related to rendering groups preventing retention points during dispose.
  27037. */
  27038. Scene.prototype.freeRenderingGroups = function () {
  27039. if (this._renderingManager) {
  27040. this._renderingManager.freeRenderingGroups();
  27041. }
  27042. if (this.textures) {
  27043. for (var i = 0; i < this.textures.length; i++) {
  27044. var texture = this.textures[i];
  27045. if (texture && texture.renderList) {
  27046. texture.freeRenderingGroups();
  27047. }
  27048. }
  27049. }
  27050. };
  27051. /** @hidden */
  27052. Scene.prototype._isInIntermediateRendering = function () {
  27053. return this._intermediateRendering;
  27054. };
  27055. /**
  27056. * Defines the current active mesh candidate provider
  27057. * @param provider defines the provider to use
  27058. */
  27059. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27060. this._activeMeshCandidateProvider = provider;
  27061. };
  27062. /**
  27063. * Gets the current active mesh candidate provider
  27064. * @returns the current active mesh candidate provider
  27065. */
  27066. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27067. return this._activeMeshCandidateProvider;
  27068. };
  27069. /**
  27070. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27071. * @returns the current scene
  27072. */
  27073. Scene.prototype.freezeActiveMeshes = function () {
  27074. if (!this.activeCamera) {
  27075. return this;
  27076. }
  27077. if (!this._frustumPlanes) {
  27078. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27079. }
  27080. this._evaluateActiveMeshes();
  27081. this._activeMeshesFrozen = true;
  27082. return this;
  27083. };
  27084. /**
  27085. * Use this function to restart evaluating active meshes on every frame
  27086. * @returns the current scene
  27087. */
  27088. Scene.prototype.unfreezeActiveMeshes = function () {
  27089. this._activeMeshesFrozen = false;
  27090. return this;
  27091. };
  27092. Scene.prototype._evaluateActiveMeshes = function () {
  27093. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27094. return;
  27095. }
  27096. if (!this.activeCamera) {
  27097. return;
  27098. }
  27099. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27100. this.activeCamera._activeMeshes.reset();
  27101. this._activeMeshes.reset();
  27102. this._renderingManager.reset();
  27103. this._processedMaterials.reset();
  27104. this._activeParticleSystems.reset();
  27105. this._activeSkeletons.reset();
  27106. this._softwareSkinnedMeshes.reset();
  27107. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27108. var step = _a[_i];
  27109. step.action();
  27110. }
  27111. // Meshes
  27112. var meshes;
  27113. var len;
  27114. var checkIsEnabled = true;
  27115. // Determine mesh candidates
  27116. if (this._activeMeshCandidateProvider !== undefined) {
  27117. // Use _activeMeshCandidateProvider
  27118. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27119. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27120. if (meshes !== undefined) {
  27121. len = meshes.length;
  27122. }
  27123. else {
  27124. len = 0;
  27125. }
  27126. }
  27127. else if (this._selectionOctree !== undefined) {
  27128. // Octree
  27129. var selection = this._selectionOctree.select(this._frustumPlanes);
  27130. meshes = selection.data;
  27131. len = selection.length;
  27132. }
  27133. else {
  27134. // Full scene traversal
  27135. len = this.meshes.length;
  27136. meshes = this.meshes;
  27137. }
  27138. // Check each mesh
  27139. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27140. mesh = meshes[meshIndex];
  27141. if (mesh.isBlocked) {
  27142. continue;
  27143. }
  27144. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27145. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27146. continue;
  27147. }
  27148. mesh.computeWorldMatrix();
  27149. // Intersections
  27150. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27151. this._meshesForIntersections.pushNoDuplicate(mesh);
  27152. }
  27153. // Switch to current LOD
  27154. meshLOD = mesh.getLOD(this.activeCamera);
  27155. if (meshLOD === undefined || meshLOD === null) {
  27156. continue;
  27157. }
  27158. mesh._preActivate();
  27159. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27160. this._activeMeshes.push(mesh);
  27161. this.activeCamera._activeMeshes.push(mesh);
  27162. mesh._activate(this._renderId);
  27163. if (meshLOD !== mesh) {
  27164. meshLOD._activate(this._renderId);
  27165. }
  27166. this._activeMesh(mesh, meshLOD);
  27167. }
  27168. }
  27169. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27170. // Particle systems
  27171. if (this.particlesEnabled) {
  27172. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27173. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27174. var particleSystem = this.particleSystems[particleIndex];
  27175. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27176. continue;
  27177. }
  27178. var emitter = particleSystem.emitter;
  27179. if (!emitter.position || emitter.isEnabled()) {
  27180. this._activeParticleSystems.push(particleSystem);
  27181. particleSystem.animate();
  27182. this._renderingManager.dispatchParticles(particleSystem);
  27183. }
  27184. }
  27185. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27186. }
  27187. };
  27188. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27189. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27190. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27191. mesh.skeleton.prepare();
  27192. }
  27193. if (!mesh.computeBonesUsingShaders) {
  27194. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27195. }
  27196. }
  27197. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27198. var step = _a[_i];
  27199. step.action(sourceMesh, mesh);
  27200. }
  27201. if (mesh !== undefined && mesh !== null
  27202. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27203. // Submeshes Octrees
  27204. var len;
  27205. var subMeshes;
  27206. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27207. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27208. len = intersections.length;
  27209. subMeshes = intersections.data;
  27210. }
  27211. else {
  27212. subMeshes = mesh.subMeshes;
  27213. len = subMeshes.length;
  27214. }
  27215. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27216. subMesh = subMeshes[subIndex];
  27217. this._evaluateSubMesh(subMesh, mesh);
  27218. }
  27219. }
  27220. };
  27221. /**
  27222. * Update the transform matrix to update from the current active camera
  27223. * @param force defines a boolean used to force the update even if cache is up to date
  27224. */
  27225. Scene.prototype.updateTransformMatrix = function (force) {
  27226. if (!this.activeCamera) {
  27227. return;
  27228. }
  27229. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27230. };
  27231. /**
  27232. * 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)
  27233. * @param alternateCamera defines the camera to use
  27234. */
  27235. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27236. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27237. };
  27238. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27239. if (camera && camera._skipRendering) {
  27240. return;
  27241. }
  27242. var engine = this._engine;
  27243. this.activeCamera = camera;
  27244. if (!this.activeCamera)
  27245. throw new Error("Active camera not set");
  27246. // Viewport
  27247. engine.setViewport(this.activeCamera.viewport);
  27248. // Camera
  27249. this.resetCachedMaterial();
  27250. this._renderId++;
  27251. this.updateTransformMatrix();
  27252. if (camera._alternateCamera) {
  27253. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27254. this._alternateRendering = true;
  27255. }
  27256. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27257. // Meshes
  27258. this._evaluateActiveMeshes();
  27259. // Software skinning
  27260. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27261. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27262. mesh.applySkeleton(mesh.skeleton);
  27263. }
  27264. // Render targets
  27265. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27266. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27267. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27268. }
  27269. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27270. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27271. }
  27272. if (this.renderTargetsEnabled) {
  27273. this._intermediateRendering = true;
  27274. if (this._renderTargets.length > 0) {
  27275. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27276. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27277. var renderTarget = this._renderTargets.data[renderIndex];
  27278. if (renderTarget._shouldRender()) {
  27279. this._renderId++;
  27280. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27281. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27282. }
  27283. }
  27284. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27285. this._renderId++;
  27286. }
  27287. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27288. var step = _a[_i];
  27289. step.action(this.activeCamera);
  27290. }
  27291. this._intermediateRendering = false;
  27292. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27293. }
  27294. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27295. // Prepare Frame
  27296. if (this.postProcessManager) {
  27297. this.postProcessManager._prepareFrame();
  27298. }
  27299. // Before Camera Draw
  27300. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27301. var step = _c[_b];
  27302. step.action(this.activeCamera);
  27303. }
  27304. // Render
  27305. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27306. this._renderingManager.render(null, null, true, true);
  27307. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27308. // After Camera Draw
  27309. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27310. var step = _e[_d];
  27311. step.action(this.activeCamera);
  27312. }
  27313. // Finalize frame
  27314. if (this.postProcessManager) {
  27315. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27316. }
  27317. // Reset some special arrays
  27318. this._renderTargets.reset();
  27319. this._alternateRendering = false;
  27320. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27321. };
  27322. Scene.prototype._processSubCameras = function (camera) {
  27323. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27324. this._renderForCamera(camera);
  27325. return;
  27326. }
  27327. // rig cameras
  27328. for (var index = 0; index < camera._rigCameras.length; index++) {
  27329. this._renderForCamera(camera._rigCameras[index], camera);
  27330. }
  27331. this.activeCamera = camera;
  27332. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27333. };
  27334. Scene.prototype._checkIntersections = function () {
  27335. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27336. var sourceMesh = this._meshesForIntersections.data[index];
  27337. if (!sourceMesh.actionManager) {
  27338. continue;
  27339. }
  27340. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27341. var action = sourceMesh.actionManager.actions[actionIndex];
  27342. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27343. var parameters = action.getTriggerParameter();
  27344. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27345. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27346. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27347. if (areIntersecting && currentIntersectionInProgress === -1) {
  27348. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27349. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27350. sourceMesh._intersectionsInProgress.push(otherMesh);
  27351. }
  27352. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27353. sourceMesh._intersectionsInProgress.push(otherMesh);
  27354. }
  27355. }
  27356. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27357. //They intersected, and now they don't.
  27358. //is this trigger an exit trigger? execute an event.
  27359. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27360. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27361. }
  27362. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27363. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27364. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27365. return otherMesh === parameterMesh;
  27366. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27367. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27368. }
  27369. }
  27370. }
  27371. }
  27372. }
  27373. };
  27374. /**
  27375. * Render the scene
  27376. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27377. */
  27378. Scene.prototype.render = function (updateCameras) {
  27379. if (updateCameras === void 0) { updateCameras = true; }
  27380. if (this.isDisposed) {
  27381. return;
  27382. }
  27383. // Register components that have been associated lately to the scene.
  27384. this._registerTransientComponents();
  27385. this._activeParticles.fetchNewFrame();
  27386. this._totalVertices.fetchNewFrame();
  27387. this._activeIndices.fetchNewFrame();
  27388. this._activeBones.fetchNewFrame();
  27389. this._meshesForIntersections.reset();
  27390. this.resetCachedMaterial();
  27391. this.onBeforeAnimationsObservable.notifyObservers(this);
  27392. // Actions
  27393. if (this.actionManager) {
  27394. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27395. }
  27396. //Simplification Queue
  27397. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27398. this.simplificationQueue.executeNext();
  27399. }
  27400. if (this._engine.isDeterministicLockStep()) {
  27401. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27402. var defaultFPS = (60.0 / 1000.0);
  27403. var defaultFrameTime = 1000 / 60; // frame time in MS
  27404. if (this._physicsEngine) {
  27405. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27406. }
  27407. var stepsTaken = 0;
  27408. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27409. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27410. internalSteps = Math.min(internalSteps, maxSubSteps);
  27411. do {
  27412. this.onBeforeStepObservable.notifyObservers(this);
  27413. // Animations
  27414. this._animationRatio = defaultFrameTime * defaultFPS;
  27415. this._animate();
  27416. this.onAfterAnimationsObservable.notifyObservers(this);
  27417. // Physics
  27418. if (this._physicsEngine) {
  27419. this.onBeforePhysicsObservable.notifyObservers(this);
  27420. this._physicsEngine._step(defaultFrameTime / 1000);
  27421. this.onAfterPhysicsObservable.notifyObservers(this);
  27422. }
  27423. this.onAfterStepObservable.notifyObservers(this);
  27424. this._currentStepId++;
  27425. stepsTaken++;
  27426. deltaTime -= defaultFrameTime;
  27427. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27428. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27429. }
  27430. else {
  27431. // Animations
  27432. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27433. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27434. this._animate();
  27435. this.onAfterAnimationsObservable.notifyObservers(this);
  27436. // Physics
  27437. if (this._physicsEngine) {
  27438. this.onBeforePhysicsObservable.notifyObservers(this);
  27439. this._physicsEngine._step(deltaTime / 1000.0);
  27440. this.onAfterPhysicsObservable.notifyObservers(this);
  27441. }
  27442. }
  27443. // Before camera update steps
  27444. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27445. var step = _a[_i];
  27446. step.action();
  27447. }
  27448. // Update Cameras
  27449. if (updateCameras) {
  27450. if (this.activeCameras.length > 0) {
  27451. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27452. var camera = this.activeCameras[cameraIndex];
  27453. camera.update();
  27454. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27455. // rig cameras
  27456. for (var index = 0; index < camera._rigCameras.length; index++) {
  27457. camera._rigCameras[index].update();
  27458. }
  27459. }
  27460. }
  27461. }
  27462. else if (this.activeCamera) {
  27463. this.activeCamera.update();
  27464. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27465. // rig cameras
  27466. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27467. this.activeCamera._rigCameras[index].update();
  27468. }
  27469. }
  27470. }
  27471. }
  27472. // Before render
  27473. this.onBeforeRenderObservable.notifyObservers(this);
  27474. // Customs render targets
  27475. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27476. var engine = this.getEngine();
  27477. var currentActiveCamera = this.activeCamera;
  27478. if (this.renderTargetsEnabled) {
  27479. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27480. this._intermediateRendering = true;
  27481. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27482. var renderTarget = this.customRenderTargets[customIndex];
  27483. if (renderTarget._shouldRender()) {
  27484. this._renderId++;
  27485. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27486. if (!this.activeCamera)
  27487. throw new Error("Active camera not set");
  27488. // Viewport
  27489. engine.setViewport(this.activeCamera.viewport);
  27490. // Camera
  27491. this.updateTransformMatrix();
  27492. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27493. }
  27494. }
  27495. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27496. this._intermediateRendering = false;
  27497. this._renderId++;
  27498. }
  27499. // Restore back buffer
  27500. if (this.customRenderTargets.length > 0) {
  27501. engine.restoreDefaultFramebuffer();
  27502. }
  27503. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27504. this.activeCamera = currentActiveCamera;
  27505. // Procedural textures
  27506. if (this.proceduralTexturesEnabled) {
  27507. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27508. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27509. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27510. if (proceduralTexture._shouldRender()) {
  27511. proceduralTexture.render();
  27512. }
  27513. }
  27514. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27515. }
  27516. // Clear
  27517. if (this.autoClearDepthAndStencil || this.autoClear) {
  27518. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27519. }
  27520. // Shadows
  27521. if (this.shadowsEnabled) {
  27522. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27523. var light = this.lights[lightIndex];
  27524. var shadowGenerator = light.getShadowGenerator();
  27525. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27526. var shadowMap = (shadowGenerator.getShadowMap());
  27527. if (this.textures.indexOf(shadowMap) !== -1) {
  27528. this._renderTargets.push(shadowMap);
  27529. }
  27530. }
  27531. }
  27532. }
  27533. // Depth renderer
  27534. for (var key in this._depthRenderer) {
  27535. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27536. }
  27537. // Geometry renderer
  27538. if (this._geometryBufferRenderer) {
  27539. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27540. }
  27541. // RenderPipeline
  27542. if (this._postProcessRenderPipelineManager) {
  27543. this._postProcessRenderPipelineManager.update();
  27544. }
  27545. // Multi-cameras?
  27546. if (this.activeCameras.length > 0) {
  27547. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27548. if (cameraIndex > 0) {
  27549. this._engine.clear(null, false, true, true);
  27550. }
  27551. this._processSubCameras(this.activeCameras[cameraIndex]);
  27552. }
  27553. }
  27554. else {
  27555. if (!this.activeCamera) {
  27556. throw new Error("No camera defined");
  27557. }
  27558. this._processSubCameras(this.activeCamera);
  27559. }
  27560. // Intersection checks
  27561. this._checkIntersections();
  27562. // Update the audio listener attached to the camera
  27563. if (BABYLON.AudioEngine) {
  27564. this._updateAudioParameters();
  27565. }
  27566. // After render
  27567. if (this.afterRender) {
  27568. this.afterRender();
  27569. }
  27570. this.onAfterRenderObservable.notifyObservers(this);
  27571. // Cleaning
  27572. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27573. var data = this._toBeDisposed.data[index];
  27574. if (data) {
  27575. data.dispose();
  27576. }
  27577. this._toBeDisposed[index] = null;
  27578. }
  27579. this._toBeDisposed.reset();
  27580. if (this.dumpNextRenderTargets) {
  27581. this.dumpNextRenderTargets = false;
  27582. }
  27583. this._activeBones.addCount(0, true);
  27584. this._activeIndices.addCount(0, true);
  27585. this._activeParticles.addCount(0, true);
  27586. };
  27587. Scene.prototype._updateAudioParameters = function () {
  27588. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27589. return;
  27590. }
  27591. var listeningCamera;
  27592. var audioEngine = BABYLON.Engine.audioEngine;
  27593. if (this.activeCameras.length > 0) {
  27594. listeningCamera = this.activeCameras[0];
  27595. }
  27596. else {
  27597. listeningCamera = this.activeCamera;
  27598. }
  27599. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27600. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27601. // for VR cameras
  27602. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27603. listeningCamera = listeningCamera.rigCameras[0];
  27604. }
  27605. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27606. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27607. cameraDirection.normalize();
  27608. // To avoid some errors on GearVR
  27609. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27610. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27611. }
  27612. var i;
  27613. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27614. var sound = this.mainSoundTrack.soundCollection[i];
  27615. if (sound.useCustomAttenuation) {
  27616. sound.updateDistanceFromListener();
  27617. }
  27618. }
  27619. for (i = 0; i < this.soundTracks.length; i++) {
  27620. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27621. sound = this.soundTracks[i].soundCollection[j];
  27622. if (sound.useCustomAttenuation) {
  27623. sound.updateDistanceFromListener();
  27624. }
  27625. }
  27626. }
  27627. }
  27628. };
  27629. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27630. // Audio
  27631. /**
  27632. * Gets or sets if audio support is enabled
  27633. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27634. */
  27635. get: function () {
  27636. return this._audioEnabled;
  27637. },
  27638. set: function (value) {
  27639. this._audioEnabled = value;
  27640. if (BABYLON.AudioEngine) {
  27641. if (this._audioEnabled) {
  27642. this._enableAudio();
  27643. }
  27644. else {
  27645. this._disableAudio();
  27646. }
  27647. }
  27648. },
  27649. enumerable: true,
  27650. configurable: true
  27651. });
  27652. Scene.prototype._disableAudio = function () {
  27653. var i;
  27654. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27655. this.mainSoundTrack.soundCollection[i].pause();
  27656. }
  27657. for (i = 0; i < this.soundTracks.length; i++) {
  27658. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27659. this.soundTracks[i].soundCollection[j].pause();
  27660. }
  27661. }
  27662. };
  27663. Scene.prototype._enableAudio = function () {
  27664. var i;
  27665. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27666. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27667. this.mainSoundTrack.soundCollection[i].play();
  27668. }
  27669. }
  27670. for (i = 0; i < this.soundTracks.length; i++) {
  27671. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27672. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27673. this.soundTracks[i].soundCollection[j].play();
  27674. }
  27675. }
  27676. }
  27677. };
  27678. Object.defineProperty(Scene.prototype, "headphone", {
  27679. /**
  27680. * Gets or sets if audio will be output to headphones
  27681. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27682. */
  27683. get: function () {
  27684. return this._headphone;
  27685. },
  27686. set: function (value) {
  27687. this._headphone = value;
  27688. if (BABYLON.AudioEngine) {
  27689. if (this._headphone) {
  27690. this._switchAudioModeForHeadphones();
  27691. }
  27692. else {
  27693. this._switchAudioModeForNormalSpeakers();
  27694. }
  27695. }
  27696. },
  27697. enumerable: true,
  27698. configurable: true
  27699. });
  27700. Scene.prototype._switchAudioModeForHeadphones = function () {
  27701. this.mainSoundTrack.switchPanningModelToHRTF();
  27702. for (var i = 0; i < this.soundTracks.length; i++) {
  27703. this.soundTracks[i].switchPanningModelToHRTF();
  27704. }
  27705. };
  27706. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27707. this.mainSoundTrack.switchPanningModelToEqualPower();
  27708. for (var i = 0; i < this.soundTracks.length; i++) {
  27709. this.soundTracks[i].switchPanningModelToEqualPower();
  27710. }
  27711. };
  27712. /**
  27713. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27714. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27715. * @returns the created depth renderer
  27716. */
  27717. Scene.prototype.enableDepthRenderer = function (camera) {
  27718. camera = camera || this.activeCamera;
  27719. if (!camera) {
  27720. throw "No camera available to enable depth renderer";
  27721. }
  27722. if (!this._depthRenderer[camera.id]) {
  27723. var textureType = 0;
  27724. if (this._engine.getCaps().textureHalfFloatRender) {
  27725. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27726. }
  27727. else if (this._engine.getCaps().textureFloatRender) {
  27728. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27729. }
  27730. else {
  27731. throw "Depth renderer does not support int texture type";
  27732. }
  27733. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27734. }
  27735. return this._depthRenderer[camera.id];
  27736. };
  27737. /**
  27738. * Disables a depth renderer for a given camera
  27739. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27740. */
  27741. Scene.prototype.disableDepthRenderer = function (camera) {
  27742. camera = camera || this.activeCamera;
  27743. if (!camera || !this._depthRenderer[camera.id]) {
  27744. return;
  27745. }
  27746. this._depthRenderer[camera.id].dispose();
  27747. delete this._depthRenderer[camera.id];
  27748. };
  27749. /**
  27750. * Enables a GeometryBufferRender and associates it with the scene
  27751. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27752. * @returns the GeometryBufferRenderer
  27753. */
  27754. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27755. if (ratio === void 0) { ratio = 1; }
  27756. if (this._geometryBufferRenderer) {
  27757. return this._geometryBufferRenderer;
  27758. }
  27759. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27760. if (!this._geometryBufferRenderer.isSupported) {
  27761. this._geometryBufferRenderer = null;
  27762. }
  27763. return this._geometryBufferRenderer;
  27764. };
  27765. /**
  27766. * Disables the GeometryBufferRender associated with the scene
  27767. */
  27768. Scene.prototype.disableGeometryBufferRenderer = function () {
  27769. if (!this._geometryBufferRenderer) {
  27770. return;
  27771. }
  27772. this._geometryBufferRenderer.dispose();
  27773. this._geometryBufferRenderer = null;
  27774. };
  27775. /**
  27776. * Freeze all materials
  27777. * A frozen material will not be updatable but should be faster to render
  27778. */
  27779. Scene.prototype.freezeMaterials = function () {
  27780. for (var i = 0; i < this.materials.length; i++) {
  27781. this.materials[i].freeze();
  27782. }
  27783. };
  27784. /**
  27785. * Unfreeze all materials
  27786. * A frozen material will not be updatable but should be faster to render
  27787. */
  27788. Scene.prototype.unfreezeMaterials = function () {
  27789. for (var i = 0; i < this.materials.length; i++) {
  27790. this.materials[i].unfreeze();
  27791. }
  27792. };
  27793. /**
  27794. * Releases all held ressources
  27795. */
  27796. Scene.prototype.dispose = function () {
  27797. this.beforeRender = null;
  27798. this.afterRender = null;
  27799. this.skeletons = [];
  27800. this.morphTargetManagers = [];
  27801. this._transientComponents = [];
  27802. this._isReadyForMeshStage.clear();
  27803. this._beforeEvaluateActiveMeshStage.clear();
  27804. this._evaluateSubMeshStage.clear();
  27805. this._activeMeshStage.clear();
  27806. this._cameraDrawRenderTargetStage.clear();
  27807. this._beforeCameraDrawStage.clear();
  27808. this._beforeRenderingGroupDrawStage.clear();
  27809. this._afterRenderingGroupDrawStage.clear();
  27810. this._afterCameraDrawStage.clear();
  27811. this._beforeCameraUpdateStage.clear();
  27812. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  27813. var component = _a[_i];
  27814. component.dispose();
  27815. }
  27816. this.importedMeshesFiles = new Array();
  27817. this.stopAllAnimations();
  27818. this.resetCachedMaterial();
  27819. for (var key in this._depthRenderer) {
  27820. this._depthRenderer[key].dispose();
  27821. }
  27822. // Smart arrays
  27823. if (this.activeCamera) {
  27824. this.activeCamera._activeMeshes.dispose();
  27825. this.activeCamera = null;
  27826. }
  27827. this._activeMeshes.dispose();
  27828. this._renderingManager.dispose();
  27829. this._processedMaterials.dispose();
  27830. this._activeParticleSystems.dispose();
  27831. this._activeSkeletons.dispose();
  27832. this._softwareSkinnedMeshes.dispose();
  27833. this._renderTargets.dispose();
  27834. this._registeredForLateAnimationBindings.dispose();
  27835. this._meshesForIntersections.dispose();
  27836. this._toBeDisposed.dispose();
  27837. // Abort active requests
  27838. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  27839. var request = _c[_b];
  27840. request.abort();
  27841. }
  27842. // Debug layer
  27843. if (this._debugLayer) {
  27844. this._debugLayer.hide();
  27845. }
  27846. // Events
  27847. this.onDisposeObservable.notifyObservers(this);
  27848. this.onDisposeObservable.clear();
  27849. this.onBeforeRenderObservable.clear();
  27850. this.onAfterRenderObservable.clear();
  27851. this.onBeforeRenderTargetsRenderObservable.clear();
  27852. this.onAfterRenderTargetsRenderObservable.clear();
  27853. this.onAfterStepObservable.clear();
  27854. this.onBeforeStepObservable.clear();
  27855. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27856. this.onAfterActiveMeshesEvaluationObservable.clear();
  27857. this.onBeforeParticlesRenderingObservable.clear();
  27858. this.onAfterParticlesRenderingObservable.clear();
  27859. this.onBeforeSpritesRenderingObservable.clear();
  27860. this.onAfterSpritesRenderingObservable.clear();
  27861. this.onBeforeDrawPhaseObservable.clear();
  27862. this.onAfterDrawPhaseObservable.clear();
  27863. this.onBeforePhysicsObservable.clear();
  27864. this.onAfterPhysicsObservable.clear();
  27865. this.onBeforeAnimationsObservable.clear();
  27866. this.onAfterAnimationsObservable.clear();
  27867. this.onDataLoadedObservable.clear();
  27868. this.onBeforeRenderingGroupObservable.clear();
  27869. this.onAfterRenderingGroupObservable.clear();
  27870. this.detachControl();
  27871. // Release sounds & sounds tracks
  27872. if (BABYLON.AudioEngine) {
  27873. this.disposeSounds();
  27874. }
  27875. // VR Helper
  27876. if (this.VRHelper) {
  27877. this.VRHelper.dispose();
  27878. }
  27879. // Detach cameras
  27880. var canvas = this._engine.getRenderingCanvas();
  27881. if (canvas) {
  27882. var index;
  27883. for (index = 0; index < this.cameras.length; index++) {
  27884. this.cameras[index].detachControl(canvas);
  27885. }
  27886. }
  27887. // Release animation groups
  27888. while (this.animationGroups.length) {
  27889. this.animationGroups[0].dispose();
  27890. }
  27891. // Release lights
  27892. while (this.lights.length) {
  27893. this.lights[0].dispose();
  27894. }
  27895. // Release meshes
  27896. while (this.meshes.length) {
  27897. this.meshes[0].dispose(true);
  27898. }
  27899. while (this.transformNodes.length) {
  27900. this.removeTransformNode(this.transformNodes[0]);
  27901. }
  27902. // Release cameras
  27903. while (this.cameras.length) {
  27904. this.cameras[0].dispose();
  27905. }
  27906. // Release materials
  27907. if (this.defaultMaterial) {
  27908. this.defaultMaterial.dispose();
  27909. }
  27910. while (this.multiMaterials.length) {
  27911. this.multiMaterials[0].dispose();
  27912. }
  27913. while (this.materials.length) {
  27914. this.materials[0].dispose();
  27915. }
  27916. // Release particles
  27917. while (this.particleSystems.length) {
  27918. this.particleSystems[0].dispose();
  27919. }
  27920. // Release sprites
  27921. while (this.spriteManagers.length) {
  27922. this.spriteManagers[0].dispose();
  27923. }
  27924. // Release postProcesses
  27925. while (this.postProcesses.length) {
  27926. this.postProcesses[0].dispose();
  27927. }
  27928. // Release textures
  27929. while (this.textures.length) {
  27930. this.textures[0].dispose();
  27931. }
  27932. // Release UBO
  27933. this._sceneUbo.dispose();
  27934. if (this._alternateSceneUbo) {
  27935. this._alternateSceneUbo.dispose();
  27936. }
  27937. // Post-processes
  27938. this.postProcessManager.dispose();
  27939. if (this._postProcessRenderPipelineManager) {
  27940. this._postProcessRenderPipelineManager.dispose();
  27941. }
  27942. // Physics
  27943. if (this._physicsEngine) {
  27944. this.disablePhysicsEngine();
  27945. }
  27946. // Remove from engine
  27947. index = this._engine.scenes.indexOf(this);
  27948. if (index > -1) {
  27949. this._engine.scenes.splice(index, 1);
  27950. }
  27951. this._engine.wipeCaches(true);
  27952. this._isDisposed = true;
  27953. };
  27954. Object.defineProperty(Scene.prototype, "isDisposed", {
  27955. /**
  27956. * Gets if the scene is already disposed
  27957. */
  27958. get: function () {
  27959. return this._isDisposed;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. /**
  27965. * Releases sounds & soundtracks
  27966. */
  27967. Scene.prototype.disposeSounds = function () {
  27968. if (!this._mainSoundTrack) {
  27969. return;
  27970. }
  27971. this.mainSoundTrack.dispose();
  27972. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27973. this.soundTracks[scIndex].dispose();
  27974. }
  27975. };
  27976. /**
  27977. * Call this function to reduce memory footprint of the scene.
  27978. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  27979. */
  27980. Scene.prototype.clearCachedVertexData = function () {
  27981. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27982. var mesh = this.meshes[meshIndex];
  27983. var geometry = mesh.geometry;
  27984. if (geometry) {
  27985. geometry._indices = [];
  27986. for (var vbName in geometry._vertexBuffers) {
  27987. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  27988. continue;
  27989. }
  27990. geometry._vertexBuffers[vbName]._buffer._data = null;
  27991. }
  27992. }
  27993. }
  27994. };
  27995. /**
  27996. * This function will remove the local cached buffer data from texture.
  27997. * It will save memory but will prevent the texture from being rebuilt
  27998. */
  27999. Scene.prototype.cleanCachedTextureBuffer = function () {
  28000. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28001. var baseTexture = _a[_i];
  28002. var buffer = baseTexture._buffer;
  28003. if (buffer) {
  28004. baseTexture._buffer = null;
  28005. }
  28006. }
  28007. };
  28008. // Octrees
  28009. /**
  28010. * Get the world extend vectors with an optional filter
  28011. *
  28012. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28013. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28014. */
  28015. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28016. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28017. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28018. filterPredicate = filterPredicate || (function () { return true; });
  28019. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28020. mesh.computeWorldMatrix(true);
  28021. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28022. return;
  28023. }
  28024. var boundingInfo = mesh.getBoundingInfo();
  28025. var minBox = boundingInfo.boundingBox.minimumWorld;
  28026. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28027. BABYLON.Tools.CheckExtends(minBox, min, max);
  28028. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28029. });
  28030. return {
  28031. min: min,
  28032. max: max
  28033. };
  28034. };
  28035. /**
  28036. * Creates or updates the octree used to boost selection (picking)
  28037. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28038. * @param maxCapacity defines the maximum capacity per leaf
  28039. * @param maxDepth defines the maximum depth of the octree
  28040. * @returns an octree of AbstractMesh
  28041. */
  28042. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28043. if (maxCapacity === void 0) { maxCapacity = 64; }
  28044. if (maxDepth === void 0) { maxDepth = 2; }
  28045. if (!this._selectionOctree) {
  28046. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28047. }
  28048. var worldExtends = this.getWorldExtends();
  28049. // Update octree
  28050. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28051. return this._selectionOctree;
  28052. };
  28053. // Picking
  28054. /**
  28055. * Creates a ray that can be used to pick in the scene
  28056. * @param x defines the x coordinate of the origin (on-screen)
  28057. * @param y defines the y coordinate of the origin (on-screen)
  28058. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28059. * @param camera defines the camera to use for the picking
  28060. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28061. * @returns a Ray
  28062. */
  28063. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28064. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28065. var result = BABYLON.Ray.Zero();
  28066. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28067. return result;
  28068. };
  28069. /**
  28070. * Creates a ray that can be used to pick in the scene
  28071. * @param x defines the x coordinate of the origin (on-screen)
  28072. * @param y defines the y coordinate of the origin (on-screen)
  28073. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28074. * @param result defines the ray where to store the picking ray
  28075. * @param camera defines the camera to use for the picking
  28076. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28077. * @returns the current scene
  28078. */
  28079. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28080. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28081. var engine = this._engine;
  28082. if (!camera) {
  28083. if (!this.activeCamera)
  28084. throw new Error("Active camera not set");
  28085. camera = this.activeCamera;
  28086. }
  28087. var cameraViewport = camera.viewport;
  28088. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28089. // Moving coordinates to local viewport world
  28090. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28091. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28092. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28093. return this;
  28094. };
  28095. /**
  28096. * Creates a ray that can be used to pick in the scene
  28097. * @param x defines the x coordinate of the origin (on-screen)
  28098. * @param y defines the y coordinate of the origin (on-screen)
  28099. * @param camera defines the camera to use for the picking
  28100. * @returns a Ray
  28101. */
  28102. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28103. var result = BABYLON.Ray.Zero();
  28104. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28105. return result;
  28106. };
  28107. /**
  28108. * Creates a ray that can be used to pick in the scene
  28109. * @param x defines the x coordinate of the origin (on-screen)
  28110. * @param y defines the y coordinate of the origin (on-screen)
  28111. * @param result defines the ray where to store the picking ray
  28112. * @param camera defines the camera to use for the picking
  28113. * @returns the current scene
  28114. */
  28115. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28116. if (!BABYLON.PickingInfo) {
  28117. return this;
  28118. }
  28119. var engine = this._engine;
  28120. if (!camera) {
  28121. if (!this.activeCamera)
  28122. throw new Error("Active camera not set");
  28123. camera = this.activeCamera;
  28124. }
  28125. var cameraViewport = camera.viewport;
  28126. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28127. var identity = BABYLON.Matrix.Identity();
  28128. // Moving coordinates to local viewport world
  28129. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28130. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28131. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28132. return this;
  28133. };
  28134. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28135. if (!BABYLON.PickingInfo) {
  28136. return null;
  28137. }
  28138. var pickingInfo = null;
  28139. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28140. var mesh = this.meshes[meshIndex];
  28141. if (predicate) {
  28142. if (!predicate(mesh)) {
  28143. continue;
  28144. }
  28145. }
  28146. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28147. continue;
  28148. }
  28149. var world = mesh.getWorldMatrix();
  28150. var ray = rayFunction(world);
  28151. var result = mesh.intersects(ray, fastCheck);
  28152. if (!result || !result.hit)
  28153. continue;
  28154. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28155. continue;
  28156. pickingInfo = result;
  28157. if (fastCheck) {
  28158. break;
  28159. }
  28160. }
  28161. return pickingInfo || new BABYLON.PickingInfo();
  28162. };
  28163. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28164. if (!BABYLON.PickingInfo) {
  28165. return null;
  28166. }
  28167. var pickingInfos = new Array();
  28168. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28169. var mesh = this.meshes[meshIndex];
  28170. if (predicate) {
  28171. if (!predicate(mesh)) {
  28172. continue;
  28173. }
  28174. }
  28175. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28176. continue;
  28177. }
  28178. var world = mesh.getWorldMatrix();
  28179. var ray = rayFunction(world);
  28180. var result = mesh.intersects(ray, false);
  28181. if (!result || !result.hit)
  28182. continue;
  28183. pickingInfos.push(result);
  28184. }
  28185. return pickingInfos;
  28186. };
  28187. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28188. if (!BABYLON.PickingInfo) {
  28189. return null;
  28190. }
  28191. var pickingInfo = null;
  28192. if (!camera) {
  28193. if (!this.activeCamera) {
  28194. return null;
  28195. }
  28196. camera = this.activeCamera;
  28197. }
  28198. if (this.spriteManagers.length > 0) {
  28199. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28200. var spriteManager = this.spriteManagers[spriteIndex];
  28201. if (!spriteManager.isPickable) {
  28202. continue;
  28203. }
  28204. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28205. if (!result || !result.hit)
  28206. continue;
  28207. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28208. continue;
  28209. pickingInfo = result;
  28210. if (fastCheck) {
  28211. break;
  28212. }
  28213. }
  28214. }
  28215. return pickingInfo || new BABYLON.PickingInfo();
  28216. };
  28217. /** Launch a ray to try to pick a mesh in the scene
  28218. * @param x position on screen
  28219. * @param y position on screen
  28220. * @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
  28221. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28222. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28223. * @returns a PickingInfo
  28224. */
  28225. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28226. var _this = this;
  28227. if (!BABYLON.PickingInfo) {
  28228. return null;
  28229. }
  28230. var result = this._internalPick(function (world) {
  28231. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28232. return _this._tempPickingRay;
  28233. }, predicate, fastCheck);
  28234. if (result) {
  28235. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28236. }
  28237. return result;
  28238. };
  28239. /** Launch a ray to try to pick a sprite in the scene
  28240. * @param x position on screen
  28241. * @param y position on screen
  28242. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28243. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28244. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28245. * @returns a PickingInfo
  28246. */
  28247. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28248. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28249. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28250. };
  28251. /** Use the given ray to pick a mesh in the scene
  28252. * @param ray The ray to use to pick meshes
  28253. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  28254. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28255. * @returns a PickingInfo
  28256. */
  28257. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28258. var _this = this;
  28259. var result = this._internalPick(function (world) {
  28260. if (!_this._pickWithRayInverseMatrix) {
  28261. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28262. }
  28263. world.invertToRef(_this._pickWithRayInverseMatrix);
  28264. if (!_this._cachedRayForTransform) {
  28265. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28266. }
  28267. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28268. return _this._cachedRayForTransform;
  28269. }, predicate, fastCheck);
  28270. if (result) {
  28271. result.ray = ray;
  28272. }
  28273. return result;
  28274. };
  28275. /**
  28276. * Launch a ray to try to pick a mesh in the scene
  28277. * @param x X position on screen
  28278. * @param y Y position on screen
  28279. * @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
  28280. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28281. * @returns an array of PickingInfo
  28282. */
  28283. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28284. var _this = this;
  28285. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28286. };
  28287. /**
  28288. * Launch a ray to try to pick a mesh in the scene
  28289. * @param ray Ray to use
  28290. * @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
  28291. * @returns an array of PickingInfo
  28292. */
  28293. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28294. var _this = this;
  28295. return this._internalMultiPick(function (world) {
  28296. if (!_this._pickWithRayInverseMatrix) {
  28297. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28298. }
  28299. world.invertToRef(_this._pickWithRayInverseMatrix);
  28300. if (!_this._cachedRayForTransform) {
  28301. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28302. }
  28303. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28304. return _this._cachedRayForTransform;
  28305. }, predicate);
  28306. };
  28307. /**
  28308. * Force the value of meshUnderPointer
  28309. * @param mesh defines the mesh to use
  28310. */
  28311. Scene.prototype.setPointerOverMesh = function (mesh) {
  28312. if (this._pointerOverMesh === mesh) {
  28313. return;
  28314. }
  28315. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28316. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28317. }
  28318. this._pointerOverMesh = mesh;
  28319. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28320. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28321. }
  28322. };
  28323. /**
  28324. * Gets the mesh under the pointer
  28325. * @returns a Mesh or null if no mesh is under the pointer
  28326. */
  28327. Scene.prototype.getPointerOverMesh = function () {
  28328. return this._pointerOverMesh;
  28329. };
  28330. /**
  28331. * Force the sprite under the pointer
  28332. * @param sprite defines the sprite to use
  28333. */
  28334. Scene.prototype.setPointerOverSprite = function (sprite) {
  28335. if (this._pointerOverSprite === sprite) {
  28336. return;
  28337. }
  28338. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28339. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28340. }
  28341. this._pointerOverSprite = sprite;
  28342. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28343. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28344. }
  28345. };
  28346. /**
  28347. * Gets the sprite under the pointer
  28348. * @returns a Sprite or null if no sprite is under the pointer
  28349. */
  28350. Scene.prototype.getPointerOverSprite = function () {
  28351. return this._pointerOverSprite;
  28352. };
  28353. // Physics
  28354. /**
  28355. * Gets the current physics engine
  28356. * @returns a PhysicsEngine or null if none attached
  28357. */
  28358. Scene.prototype.getPhysicsEngine = function () {
  28359. return this._physicsEngine;
  28360. };
  28361. /**
  28362. * Enables physics to the current scene
  28363. * @param gravity defines the scene's gravity for the physics engine
  28364. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28365. * @return a boolean indicating if the physics engine was initialized
  28366. */
  28367. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28368. if (gravity === void 0) { gravity = null; }
  28369. if (this._physicsEngine) {
  28370. return true;
  28371. }
  28372. try {
  28373. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28374. return true;
  28375. }
  28376. catch (e) {
  28377. BABYLON.Tools.Error(e.message);
  28378. return false;
  28379. }
  28380. };
  28381. /**
  28382. * Disables and disposes the physics engine associated with the scene
  28383. */
  28384. Scene.prototype.disablePhysicsEngine = function () {
  28385. if (!this._physicsEngine) {
  28386. return;
  28387. }
  28388. this._physicsEngine.dispose();
  28389. this._physicsEngine = null;
  28390. };
  28391. /**
  28392. * Gets a boolean indicating if there is an active physics engine
  28393. * @returns a boolean indicating if there is an active physics engine
  28394. */
  28395. Scene.prototype.isPhysicsEnabled = function () {
  28396. return this._physicsEngine !== undefined;
  28397. };
  28398. /**
  28399. * Deletes a physics compound impostor
  28400. * @param compound defines the compound to delete
  28401. */
  28402. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28403. var mesh = compound.parts[0].mesh;
  28404. if (mesh.physicsImpostor) {
  28405. mesh.physicsImpostor.dispose( /*true*/);
  28406. mesh.physicsImpostor = null;
  28407. }
  28408. };
  28409. // Misc.
  28410. /** @hidden */
  28411. Scene.prototype._rebuildGeometries = function () {
  28412. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28413. var geometry = _a[_i];
  28414. geometry._rebuild();
  28415. }
  28416. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28417. var mesh = _c[_b];
  28418. mesh._rebuild();
  28419. }
  28420. if (this.postProcessManager) {
  28421. this.postProcessManager._rebuild();
  28422. }
  28423. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28424. var component = _e[_d];
  28425. component.rebuild();
  28426. }
  28427. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28428. var system = _g[_f];
  28429. system.rebuild();
  28430. }
  28431. if (this._postProcessRenderPipelineManager) {
  28432. this._postProcessRenderPipelineManager._rebuild();
  28433. }
  28434. };
  28435. /** @hidden */
  28436. Scene.prototype._rebuildTextures = function () {
  28437. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28438. var texture = _a[_i];
  28439. texture._rebuild();
  28440. }
  28441. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28442. };
  28443. /**
  28444. * Creates a default light for the scene.
  28445. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28446. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28447. */
  28448. Scene.prototype.createDefaultLight = function (replace) {
  28449. if (replace === void 0) { replace = false; }
  28450. // Dispose existing light in replace mode.
  28451. if (replace) {
  28452. if (this.lights) {
  28453. for (var i = 0; i < this.lights.length; i++) {
  28454. this.lights[i].dispose();
  28455. }
  28456. }
  28457. }
  28458. // Light
  28459. if (this.lights.length === 0) {
  28460. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28461. }
  28462. };
  28463. /**
  28464. * Creates a default camera for the scene.
  28465. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28466. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28467. * @param replace has default false, when true replaces the active camera in the scene
  28468. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28469. */
  28470. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28471. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28472. if (replace === void 0) { replace = false; }
  28473. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28474. // Dispose existing camera in replace mode.
  28475. if (replace) {
  28476. if (this.activeCamera) {
  28477. this.activeCamera.dispose();
  28478. this.activeCamera = null;
  28479. }
  28480. }
  28481. // Camera
  28482. if (!this.activeCamera) {
  28483. var worldExtends = this.getWorldExtends();
  28484. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28485. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28486. var camera;
  28487. var radius = worldSize.length() * 1.5;
  28488. // empty scene scenario!
  28489. if (!isFinite(radius)) {
  28490. radius = 1;
  28491. worldCenter.copyFromFloats(0, 0, 0);
  28492. }
  28493. if (createArcRotateCamera) {
  28494. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28495. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28496. arcRotateCamera.wheelPrecision = 100 / radius;
  28497. camera = arcRotateCamera;
  28498. }
  28499. else {
  28500. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28501. freeCamera.setTarget(worldCenter);
  28502. camera = freeCamera;
  28503. }
  28504. camera.minZ = radius * 0.01;
  28505. camera.maxZ = radius * 1000;
  28506. camera.speed = radius * 0.2;
  28507. this.activeCamera = camera;
  28508. var canvas = this.getEngine().getRenderingCanvas();
  28509. if (attachCameraControls && canvas) {
  28510. camera.attachControl(canvas);
  28511. }
  28512. }
  28513. };
  28514. /**
  28515. * Creates a default camera and a default light.
  28516. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28517. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28518. * @param replace has the default false, when true replaces the active camera/light in the scene
  28519. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28520. */
  28521. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28522. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28523. if (replace === void 0) { replace = false; }
  28524. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28525. this.createDefaultLight(replace);
  28526. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28527. };
  28528. /**
  28529. * Creates a new sky box
  28530. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28531. * @param environmentTexture defines the texture to use as environment texture
  28532. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28533. * @param scale defines the overall scale of the skybox
  28534. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28535. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28536. * @returns a new mesh holding the sky box
  28537. */
  28538. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28539. if (pbr === void 0) { pbr = false; }
  28540. if (scale === void 0) { scale = 1000; }
  28541. if (blur === void 0) { blur = 0; }
  28542. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28543. if (!environmentTexture) {
  28544. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28545. return null;
  28546. }
  28547. if (setGlobalEnvTexture) {
  28548. if (environmentTexture) {
  28549. this.environmentTexture = environmentTexture;
  28550. }
  28551. }
  28552. // Skybox
  28553. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28554. if (pbr) {
  28555. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28556. hdrSkyboxMaterial.backFaceCulling = false;
  28557. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28558. if (hdrSkyboxMaterial.reflectionTexture) {
  28559. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28560. }
  28561. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28562. hdrSkyboxMaterial.disableLighting = true;
  28563. hdrSkyboxMaterial.twoSidedLighting = true;
  28564. hdrSkybox.infiniteDistance = true;
  28565. hdrSkybox.material = hdrSkyboxMaterial;
  28566. }
  28567. else {
  28568. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28569. skyboxMaterial.backFaceCulling = false;
  28570. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28571. if (skyboxMaterial.reflectionTexture) {
  28572. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28573. }
  28574. skyboxMaterial.disableLighting = true;
  28575. hdrSkybox.infiniteDistance = true;
  28576. hdrSkybox.material = skyboxMaterial;
  28577. }
  28578. return hdrSkybox;
  28579. };
  28580. /**
  28581. * Creates a new environment
  28582. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28583. * @param options defines the options you can use to configure the environment
  28584. * @returns the new EnvironmentHelper
  28585. */
  28586. Scene.prototype.createDefaultEnvironment = function (options) {
  28587. if (BABYLON.EnvironmentHelper) {
  28588. return new BABYLON.EnvironmentHelper(options, this);
  28589. }
  28590. return null;
  28591. };
  28592. /**
  28593. * Creates a new VREXperienceHelper
  28594. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28595. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28596. * @returns a new VREXperienceHelper
  28597. */
  28598. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28599. if (webVROptions === void 0) { webVROptions = {}; }
  28600. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28601. };
  28602. // Tags
  28603. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28604. if (tagsQuery === undefined) {
  28605. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28606. return list;
  28607. }
  28608. var listByTags = [];
  28609. forEach = forEach || (function (item) { return; });
  28610. for (var i in list) {
  28611. var item = list[i];
  28612. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28613. listByTags.push(item);
  28614. forEach(item);
  28615. }
  28616. }
  28617. return listByTags;
  28618. };
  28619. /**
  28620. * Get a list of meshes by tags
  28621. * @param tagsQuery defines the tags query to use
  28622. * @param forEach defines a predicate used to filter results
  28623. * @returns an array of Mesh
  28624. */
  28625. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28626. return this._getByTags(this.meshes, tagsQuery, forEach);
  28627. };
  28628. /**
  28629. * Get a list of cameras by tags
  28630. * @param tagsQuery defines the tags query to use
  28631. * @param forEach defines a predicate used to filter results
  28632. * @returns an array of Camera
  28633. */
  28634. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28635. return this._getByTags(this.cameras, tagsQuery, forEach);
  28636. };
  28637. /**
  28638. * Get a list of lights by tags
  28639. * @param tagsQuery defines the tags query to use
  28640. * @param forEach defines a predicate used to filter results
  28641. * @returns an array of Light
  28642. */
  28643. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28644. return this._getByTags(this.lights, tagsQuery, forEach);
  28645. };
  28646. /**
  28647. * Get a list of materials by tags
  28648. * @param tagsQuery defines the tags query to use
  28649. * @param forEach defines a predicate used to filter results
  28650. * @returns an array of Material
  28651. */
  28652. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28653. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28654. };
  28655. /**
  28656. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28657. * This allowed control for front to back rendering or reversly depending of the special needs.
  28658. *
  28659. * @param renderingGroupId The rendering group id corresponding to its index
  28660. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28661. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28662. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28663. */
  28664. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28665. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28666. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28667. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28668. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28669. };
  28670. /**
  28671. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28672. *
  28673. * @param renderingGroupId The rendering group id corresponding to its index
  28674. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28675. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28676. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28677. */
  28678. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28679. if (depth === void 0) { depth = true; }
  28680. if (stencil === void 0) { stencil = true; }
  28681. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28682. };
  28683. /**
  28684. * Gets the current auto clear configuration for one rendering group of the rendering
  28685. * manager.
  28686. * @param index the rendering group index to get the information for
  28687. * @returns The auto clear setup for the requested rendering group
  28688. */
  28689. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28690. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28691. };
  28692. /**
  28693. * Will flag all materials as dirty to trigger new shader compilation
  28694. * @param flag defines the flag used to specify which material part must be marked as dirty
  28695. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28696. */
  28697. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28698. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28699. var material = _a[_i];
  28700. if (predicate && !predicate(material)) {
  28701. continue;
  28702. }
  28703. material.markAsDirty(flag);
  28704. }
  28705. };
  28706. /** @hidden */
  28707. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28708. var _this = this;
  28709. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28710. this._activeRequests.push(request);
  28711. request.onCompleteObservable.add(function (request) {
  28712. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28713. });
  28714. return request;
  28715. };
  28716. /** @hidden */
  28717. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28718. var _this = this;
  28719. return new Promise(function (resolve, reject) {
  28720. _this._loadFile(url, function (data) {
  28721. resolve(data);
  28722. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28723. reject(exception);
  28724. });
  28725. });
  28726. };
  28727. // Statics
  28728. Scene._FOGMODE_NONE = 0;
  28729. Scene._FOGMODE_EXP = 1;
  28730. Scene._FOGMODE_EXP2 = 2;
  28731. Scene._FOGMODE_LINEAR = 3;
  28732. Scene._uniqueIdCounter = 0;
  28733. /**
  28734. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28735. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28736. */
  28737. Scene.MinDeltaTime = 1.0;
  28738. /**
  28739. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28740. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28741. */
  28742. Scene.MaxDeltaTime = 1000.0;
  28743. /** The distance in pixel that you have to move to prevent some events */
  28744. Scene.DragMovementThreshold = 10; // in pixels
  28745. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28746. Scene.LongPressDelay = 500; // in milliseconds
  28747. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28748. Scene.DoubleClickDelay = 300; // in milliseconds
  28749. /** If you need to check double click without raising a single click at first click, enable this flag */
  28750. Scene.ExclusiveDoubleClickMode = false;
  28751. return Scene;
  28752. }(BABYLON.AbstractScene));
  28753. BABYLON.Scene = Scene;
  28754. })(BABYLON || (BABYLON = {}));
  28755. //# sourceMappingURL=babylon.scene.js.map
  28756. var BABYLON;
  28757. (function (BABYLON) {
  28758. /**
  28759. * Set of assets to keep when moving a scene into an asset container.
  28760. */
  28761. var KeepAssets = /** @class */ (function (_super) {
  28762. __extends(KeepAssets, _super);
  28763. function KeepAssets() {
  28764. return _super !== null && _super.apply(this, arguments) || this;
  28765. }
  28766. return KeepAssets;
  28767. }(BABYLON.AbstractScene));
  28768. BABYLON.KeepAssets = KeepAssets;
  28769. /**
  28770. * Container with a set of assets that can be added or removed from a scene.
  28771. */
  28772. var AssetContainer = /** @class */ (function (_super) {
  28773. __extends(AssetContainer, _super);
  28774. /**
  28775. * Instantiates an AssetContainer.
  28776. * @param scene The scene the AssetContainer belongs to.
  28777. */
  28778. function AssetContainer(scene) {
  28779. var _this = _super.call(this) || this;
  28780. _this.scene = scene;
  28781. return _this;
  28782. }
  28783. /**
  28784. * Adds all the assets from the container to the scene.
  28785. */
  28786. AssetContainer.prototype.addAllToScene = function () {
  28787. var _this = this;
  28788. this.cameras.forEach(function (o) {
  28789. _this.scene.addCamera(o);
  28790. });
  28791. this.lights.forEach(function (o) {
  28792. _this.scene.addLight(o);
  28793. });
  28794. this.meshes.forEach(function (o) {
  28795. _this.scene.addMesh(o);
  28796. });
  28797. this.skeletons.forEach(function (o) {
  28798. _this.scene.addSkeleton(o);
  28799. });
  28800. this.animations.forEach(function (o) {
  28801. _this.scene.addAnimation(o);
  28802. });
  28803. this.animationGroups.forEach(function (o) {
  28804. _this.scene.addAnimationGroup(o);
  28805. });
  28806. this.multiMaterials.forEach(function (o) {
  28807. _this.scene.addMultiMaterial(o);
  28808. });
  28809. this.materials.forEach(function (o) {
  28810. _this.scene.addMaterial(o);
  28811. });
  28812. this.morphTargetManagers.forEach(function (o) {
  28813. _this.scene.addMorphTargetManager(o);
  28814. });
  28815. this.geometries.forEach(function (o) {
  28816. _this.scene.addGeometry(o);
  28817. });
  28818. this.transformNodes.forEach(function (o) {
  28819. _this.scene.addTransformNode(o);
  28820. });
  28821. this.actionManagers.forEach(function (o) {
  28822. _this.scene.addActionManager(o);
  28823. });
  28824. this.sounds.forEach(function (o) {
  28825. o.play();
  28826. o.autoplay = true;
  28827. _this.scene.mainSoundTrack.AddSound(o);
  28828. });
  28829. this.textures.forEach(function (o) {
  28830. _this.scene.addTexture(o);
  28831. });
  28832. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28833. var component = _a[_i];
  28834. component.addFromContainer(this.scene);
  28835. }
  28836. };
  28837. /**
  28838. * Removes all the assets in the container from the scene
  28839. */
  28840. AssetContainer.prototype.removeAllFromScene = function () {
  28841. var _this = this;
  28842. this.cameras.forEach(function (o) {
  28843. _this.scene.removeCamera(o);
  28844. });
  28845. this.lights.forEach(function (o) {
  28846. _this.scene.removeLight(o);
  28847. });
  28848. this.meshes.forEach(function (o) {
  28849. _this.scene.removeMesh(o);
  28850. });
  28851. this.skeletons.forEach(function (o) {
  28852. _this.scene.removeSkeleton(o);
  28853. });
  28854. this.animations.forEach(function (o) {
  28855. _this.scene.removeAnimation(o);
  28856. });
  28857. this.animationGroups.forEach(function (o) {
  28858. _this.scene.removeAnimationGroup(o);
  28859. });
  28860. this.multiMaterials.forEach(function (o) {
  28861. _this.scene.removeMultiMaterial(o);
  28862. });
  28863. this.materials.forEach(function (o) {
  28864. _this.scene.removeMaterial(o);
  28865. });
  28866. this.morphTargetManagers.forEach(function (o) {
  28867. _this.scene.removeMorphTargetManager(o);
  28868. });
  28869. this.geometries.forEach(function (o) {
  28870. _this.scene.removeGeometry(o);
  28871. });
  28872. this.transformNodes.forEach(function (o) {
  28873. _this.scene.removeTransformNode(o);
  28874. });
  28875. this.actionManagers.forEach(function (o) {
  28876. _this.scene.removeActionManager(o);
  28877. });
  28878. this.sounds.forEach(function (o) {
  28879. o.stop();
  28880. o.autoplay = false;
  28881. _this.scene.mainSoundTrack.RemoveSound(o);
  28882. });
  28883. this.textures.forEach(function (o) {
  28884. _this.scene.removeTexture(o);
  28885. });
  28886. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28887. var component = _a[_i];
  28888. component.removeFromContainer(this.scene);
  28889. }
  28890. };
  28891. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28892. if (!sourceAssets) {
  28893. return;
  28894. }
  28895. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28896. var asset = sourceAssets_1[_i];
  28897. var move = true;
  28898. if (keepAssets) {
  28899. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28900. var keepAsset = keepAssets_1[_a];
  28901. if (asset === keepAsset) {
  28902. move = false;
  28903. break;
  28904. }
  28905. }
  28906. }
  28907. if (move) {
  28908. targetAssets.push(asset);
  28909. }
  28910. }
  28911. };
  28912. /**
  28913. * Removes all the assets contained in the scene and adds them to the container.
  28914. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28915. */
  28916. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28917. if (keepAssets === undefined) {
  28918. keepAssets = new KeepAssets();
  28919. }
  28920. for (var key in this) {
  28921. if (this.hasOwnProperty(key)) {
  28922. this[key] = this[key] || [];
  28923. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28924. }
  28925. }
  28926. this.removeAllFromScene();
  28927. };
  28928. /**
  28929. * 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.
  28930. * @returns the root mesh
  28931. */
  28932. AssetContainer.prototype.createRootMesh = function () {
  28933. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28934. this.meshes.forEach(function (m) {
  28935. if (!m.parent) {
  28936. rootMesh.addChild(m);
  28937. }
  28938. });
  28939. this.meshes.unshift(rootMesh);
  28940. return rootMesh;
  28941. };
  28942. return AssetContainer;
  28943. }(BABYLON.AbstractScene));
  28944. BABYLON.AssetContainer = AssetContainer;
  28945. })(BABYLON || (BABYLON = {}));
  28946. //# sourceMappingURL=babylon.assetContainer.js.map
  28947. var BABYLON;
  28948. (function (BABYLON) {
  28949. var Buffer = /** @class */ (function () {
  28950. /**
  28951. * Constructor
  28952. * @param engine the engine
  28953. * @param data the data to use for this buffer
  28954. * @param updatable whether the data is updatable
  28955. * @param stride the stride (optional)
  28956. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28957. * @param instanced whether the buffer is instanced (optional)
  28958. * @param useBytes set to true if the stride in in bytes (optional)
  28959. */
  28960. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28961. if (stride === void 0) { stride = 0; }
  28962. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28963. if (instanced === void 0) { instanced = false; }
  28964. if (useBytes === void 0) { useBytes = false; }
  28965. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28966. this._engine = engine.getScene().getEngine();
  28967. }
  28968. else {
  28969. this._engine = engine;
  28970. }
  28971. this._updatable = updatable;
  28972. this._instanced = instanced;
  28973. this._data = data;
  28974. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28975. if (!postponeInternalCreation) { // by default
  28976. this.create();
  28977. }
  28978. }
  28979. /**
  28980. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28981. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28982. * @param offset defines offset in the buffer (0 by default)
  28983. * @param size defines the size in floats of attributes (position is 3 for instance)
  28984. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28985. * @param instanced defines if the vertex buffer contains indexed data
  28986. * @param useBytes defines if the offset and stride are in bytes
  28987. * @returns the new vertex buffer
  28988. */
  28989. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28990. if (useBytes === void 0) { useBytes = false; }
  28991. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28992. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28993. // a lot of these parameters are ignored as they are overriden by the buffer
  28994. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28995. };
  28996. // Properties
  28997. Buffer.prototype.isUpdatable = function () {
  28998. return this._updatable;
  28999. };
  29000. Buffer.prototype.getData = function () {
  29001. return this._data;
  29002. };
  29003. Buffer.prototype.getBuffer = function () {
  29004. return this._buffer;
  29005. };
  29006. /**
  29007. * Gets the stride in float32 units (i.e. byte stride / 4).
  29008. * May not be an integer if the byte stride is not divisible by 4.
  29009. * DEPRECATED. Use byteStride instead.
  29010. * @returns the stride in float32 units
  29011. */
  29012. Buffer.prototype.getStrideSize = function () {
  29013. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29014. };
  29015. // Methods
  29016. Buffer.prototype.create = function (data) {
  29017. if (data === void 0) { data = null; }
  29018. if (!data && this._buffer) {
  29019. return; // nothing to do
  29020. }
  29021. data = data || this._data;
  29022. if (!data) {
  29023. return;
  29024. }
  29025. if (!this._buffer) { // create buffer
  29026. if (this._updatable) {
  29027. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29028. this._data = data;
  29029. }
  29030. else {
  29031. this._buffer = this._engine.createVertexBuffer(data);
  29032. }
  29033. }
  29034. else if (this._updatable) { // update buffer
  29035. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29036. this._data = data;
  29037. }
  29038. };
  29039. Buffer.prototype._rebuild = function () {
  29040. this._buffer = null;
  29041. this.create(this._data);
  29042. };
  29043. Buffer.prototype.update = function (data) {
  29044. this.create(data);
  29045. };
  29046. /**
  29047. * Updates the data directly.
  29048. * @param data the new data
  29049. * @param offset the new offset
  29050. * @param vertexCount the vertex count (optional)
  29051. * @param useBytes set to true if the offset is in bytes
  29052. */
  29053. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29054. if (useBytes === void 0) { useBytes = false; }
  29055. if (!this._buffer) {
  29056. return;
  29057. }
  29058. if (this._updatable) { // update buffer
  29059. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29060. this._data = null;
  29061. }
  29062. };
  29063. Buffer.prototype.dispose = function () {
  29064. if (!this._buffer) {
  29065. return;
  29066. }
  29067. if (this._engine._releaseBuffer(this._buffer)) {
  29068. this._buffer = null;
  29069. }
  29070. };
  29071. return Buffer;
  29072. }());
  29073. BABYLON.Buffer = Buffer;
  29074. })(BABYLON || (BABYLON = {}));
  29075. //# sourceMappingURL=babylon.buffer.js.map
  29076. var BABYLON;
  29077. (function (BABYLON) {
  29078. var VertexBuffer = /** @class */ (function () {
  29079. /**
  29080. * Constructor
  29081. * @param engine the engine
  29082. * @param data the data to use for this vertex buffer
  29083. * @param kind the vertex buffer kind
  29084. * @param updatable whether the data is updatable
  29085. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29086. * @param stride the stride (optional)
  29087. * @param instanced whether the buffer is instanced (optional)
  29088. * @param offset the offset of the data (optional)
  29089. * @param size the number of components (optional)
  29090. * @param type the type of the component (optional)
  29091. * @param normalized whether the data contains normalized data (optional)
  29092. * @param useBytes set to true if stride and offset are in bytes (optional)
  29093. */
  29094. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29095. if (normalized === void 0) { normalized = false; }
  29096. if (useBytes === void 0) { useBytes = false; }
  29097. if (data instanceof BABYLON.Buffer) {
  29098. this._buffer = data;
  29099. this._ownsBuffer = false;
  29100. }
  29101. else {
  29102. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29103. this._ownsBuffer = true;
  29104. }
  29105. this._kind = kind;
  29106. if (type == undefined) {
  29107. var data_1 = this.getData();
  29108. this.type = VertexBuffer.FLOAT;
  29109. if (data_1 instanceof Int8Array)
  29110. this.type = VertexBuffer.BYTE;
  29111. else if (data_1 instanceof Uint8Array)
  29112. this.type = VertexBuffer.UNSIGNED_BYTE;
  29113. else if (data_1 instanceof Int16Array)
  29114. this.type = VertexBuffer.SHORT;
  29115. else if (data_1 instanceof Uint16Array)
  29116. this.type = VertexBuffer.UNSIGNED_SHORT;
  29117. else if (data_1 instanceof Int32Array)
  29118. this.type = VertexBuffer.INT;
  29119. else if (data_1 instanceof Uint32Array)
  29120. this.type = VertexBuffer.UNSIGNED_INT;
  29121. }
  29122. else {
  29123. this.type = type;
  29124. }
  29125. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29126. if (useBytes) {
  29127. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29128. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29129. this.byteOffset = offset || 0;
  29130. }
  29131. else {
  29132. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29133. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29134. this.byteOffset = (offset || 0) * typeByteLength;
  29135. }
  29136. this.normalized = normalized;
  29137. this._instanced = instanced !== undefined ? instanced : false;
  29138. this._instanceDivisor = instanced ? 1 : 0;
  29139. }
  29140. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29141. /**
  29142. * Gets or sets the instance divisor when in instanced mode
  29143. */
  29144. get: function () {
  29145. return this._instanceDivisor;
  29146. },
  29147. set: function (value) {
  29148. this._instanceDivisor = value;
  29149. if (value == 0) {
  29150. this._instanced = false;
  29151. }
  29152. else {
  29153. this._instanced = true;
  29154. }
  29155. },
  29156. enumerable: true,
  29157. configurable: true
  29158. });
  29159. VertexBuffer.prototype._rebuild = function () {
  29160. if (!this._buffer) {
  29161. return;
  29162. }
  29163. this._buffer._rebuild();
  29164. };
  29165. /**
  29166. * Returns the kind of the VertexBuffer (string).
  29167. */
  29168. VertexBuffer.prototype.getKind = function () {
  29169. return this._kind;
  29170. };
  29171. // Properties
  29172. /**
  29173. * Boolean : is the VertexBuffer updatable ?
  29174. */
  29175. VertexBuffer.prototype.isUpdatable = function () {
  29176. return this._buffer.isUpdatable();
  29177. };
  29178. /**
  29179. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29180. */
  29181. VertexBuffer.prototype.getData = function () {
  29182. return this._buffer.getData();
  29183. };
  29184. /**
  29185. * Returns the WebGLBuffer associated to the VertexBuffer.
  29186. */
  29187. VertexBuffer.prototype.getBuffer = function () {
  29188. return this._buffer.getBuffer();
  29189. };
  29190. /**
  29191. * Returns the stride as a multiple of the type byte length.
  29192. * DEPRECATED. Use byteStride instead.
  29193. */
  29194. VertexBuffer.prototype.getStrideSize = function () {
  29195. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29196. };
  29197. /**
  29198. * Returns the offset as a multiple of the type byte length.
  29199. * DEPRECATED. Use byteOffset instead.
  29200. */
  29201. VertexBuffer.prototype.getOffset = function () {
  29202. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29203. };
  29204. /**
  29205. * Returns the number of components per vertex attribute (integer).
  29206. */
  29207. VertexBuffer.prototype.getSize = function () {
  29208. return this._size;
  29209. };
  29210. /**
  29211. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29212. */
  29213. VertexBuffer.prototype.getIsInstanced = function () {
  29214. return this._instanced;
  29215. };
  29216. /**
  29217. * Returns the instancing divisor, zero for non-instanced (integer).
  29218. */
  29219. VertexBuffer.prototype.getInstanceDivisor = function () {
  29220. return this._instanceDivisor;
  29221. };
  29222. // Methods
  29223. /**
  29224. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29225. * Returns the created WebGLBuffer.
  29226. */
  29227. VertexBuffer.prototype.create = function (data) {
  29228. return this._buffer.create(data);
  29229. };
  29230. /**
  29231. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29232. * This function will create a new buffer if the current one is not updatable
  29233. * Returns the updated WebGLBuffer.
  29234. */
  29235. VertexBuffer.prototype.update = function (data) {
  29236. return this._buffer.update(data);
  29237. };
  29238. /**
  29239. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29240. * Returns the directly updated WebGLBuffer.
  29241. * @param data the new data
  29242. * @param offset the new offset
  29243. * @param useBytes set to true if the offset is in bytes
  29244. */
  29245. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29246. if (useBytes === void 0) { useBytes = false; }
  29247. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29248. };
  29249. /**
  29250. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29251. */
  29252. VertexBuffer.prototype.dispose = function () {
  29253. if (this._ownsBuffer) {
  29254. this._buffer.dispose();
  29255. }
  29256. };
  29257. /**
  29258. * Enumerates each value of this vertex buffer as numbers.
  29259. * @param count the number of values to enumerate
  29260. * @param callback the callback function called for each value
  29261. */
  29262. VertexBuffer.prototype.forEach = function (count, callback) {
  29263. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29264. };
  29265. Object.defineProperty(VertexBuffer, "PositionKind", {
  29266. get: function () {
  29267. return VertexBuffer._PositionKind;
  29268. },
  29269. enumerable: true,
  29270. configurable: true
  29271. });
  29272. Object.defineProperty(VertexBuffer, "NormalKind", {
  29273. get: function () {
  29274. return VertexBuffer._NormalKind;
  29275. },
  29276. enumerable: true,
  29277. configurable: true
  29278. });
  29279. Object.defineProperty(VertexBuffer, "TangentKind", {
  29280. get: function () {
  29281. return VertexBuffer._TangentKind;
  29282. },
  29283. enumerable: true,
  29284. configurable: true
  29285. });
  29286. Object.defineProperty(VertexBuffer, "UVKind", {
  29287. get: function () {
  29288. return VertexBuffer._UVKind;
  29289. },
  29290. enumerable: true,
  29291. configurable: true
  29292. });
  29293. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29294. get: function () {
  29295. return VertexBuffer._UV2Kind;
  29296. },
  29297. enumerable: true,
  29298. configurable: true
  29299. });
  29300. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29301. get: function () {
  29302. return VertexBuffer._UV3Kind;
  29303. },
  29304. enumerable: true,
  29305. configurable: true
  29306. });
  29307. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29308. get: function () {
  29309. return VertexBuffer._UV4Kind;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29315. get: function () {
  29316. return VertexBuffer._UV5Kind;
  29317. },
  29318. enumerable: true,
  29319. configurable: true
  29320. });
  29321. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29322. get: function () {
  29323. return VertexBuffer._UV6Kind;
  29324. },
  29325. enumerable: true,
  29326. configurable: true
  29327. });
  29328. Object.defineProperty(VertexBuffer, "ColorKind", {
  29329. get: function () {
  29330. return VertexBuffer._ColorKind;
  29331. },
  29332. enumerable: true,
  29333. configurable: true
  29334. });
  29335. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29336. get: function () {
  29337. return VertexBuffer._MatricesIndicesKind;
  29338. },
  29339. enumerable: true,
  29340. configurable: true
  29341. });
  29342. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29343. get: function () {
  29344. return VertexBuffer._MatricesWeightsKind;
  29345. },
  29346. enumerable: true,
  29347. configurable: true
  29348. });
  29349. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29350. get: function () {
  29351. return VertexBuffer._MatricesIndicesExtraKind;
  29352. },
  29353. enumerable: true,
  29354. configurable: true
  29355. });
  29356. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29357. get: function () {
  29358. return VertexBuffer._MatricesWeightsExtraKind;
  29359. },
  29360. enumerable: true,
  29361. configurable: true
  29362. });
  29363. /**
  29364. * Deduces the stride given a kind.
  29365. * @param kind The kind string to deduce
  29366. * @returns The deduced stride
  29367. */
  29368. VertexBuffer.DeduceStride = function (kind) {
  29369. switch (kind) {
  29370. case VertexBuffer.UVKind:
  29371. case VertexBuffer.UV2Kind:
  29372. case VertexBuffer.UV3Kind:
  29373. case VertexBuffer.UV4Kind:
  29374. case VertexBuffer.UV5Kind:
  29375. case VertexBuffer.UV6Kind:
  29376. return 2;
  29377. case VertexBuffer.NormalKind:
  29378. case VertexBuffer.PositionKind:
  29379. return 3;
  29380. case VertexBuffer.ColorKind:
  29381. case VertexBuffer.MatricesIndicesKind:
  29382. case VertexBuffer.MatricesIndicesExtraKind:
  29383. case VertexBuffer.MatricesWeightsKind:
  29384. case VertexBuffer.MatricesWeightsExtraKind:
  29385. case VertexBuffer.TangentKind:
  29386. return 4;
  29387. default:
  29388. throw new Error("Invalid kind '" + kind + "'");
  29389. }
  29390. };
  29391. /**
  29392. * Gets the byte length of the given type.
  29393. * @param type the type
  29394. * @returns the number of bytes
  29395. */
  29396. VertexBuffer.GetTypeByteLength = function (type) {
  29397. switch (type) {
  29398. case VertexBuffer.BYTE:
  29399. case VertexBuffer.UNSIGNED_BYTE:
  29400. return 1;
  29401. case VertexBuffer.SHORT:
  29402. case VertexBuffer.UNSIGNED_SHORT:
  29403. return 2;
  29404. case VertexBuffer.INT:
  29405. case VertexBuffer.FLOAT:
  29406. return 4;
  29407. default:
  29408. throw new Error("Invalid type '" + type + "'");
  29409. }
  29410. };
  29411. /**
  29412. * Enumerates each value of the given parameters as numbers.
  29413. * @param data the data to enumerate
  29414. * @param byteOffset the byte offset of the data
  29415. * @param byteStride the byte stride of the data
  29416. * @param componentCount the number of components per element
  29417. * @param componentType the type of the component
  29418. * @param count the total number of components
  29419. * @param normalized whether the data is normalized
  29420. * @param callback the callback function called for each value
  29421. */
  29422. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29423. if (data instanceof Array) {
  29424. var offset = byteOffset / 4;
  29425. var stride = byteStride / 4;
  29426. for (var index = 0; index < count; index += componentCount) {
  29427. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29428. callback(data[offset + componentIndex], index + componentIndex);
  29429. }
  29430. offset += stride;
  29431. }
  29432. }
  29433. else {
  29434. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29435. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29436. for (var index = 0; index < count; index += componentCount) {
  29437. var componentByteOffset = byteOffset;
  29438. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29439. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29440. callback(value, index + componentIndex);
  29441. componentByteOffset += componentByteLength;
  29442. }
  29443. byteOffset += byteStride;
  29444. }
  29445. }
  29446. };
  29447. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29448. switch (type) {
  29449. case VertexBuffer.BYTE: {
  29450. var value = dataView.getInt8(byteOffset);
  29451. if (normalized) {
  29452. value = Math.max(value / 127, -1);
  29453. }
  29454. return value;
  29455. }
  29456. case VertexBuffer.UNSIGNED_BYTE: {
  29457. var value = dataView.getUint8(byteOffset);
  29458. if (normalized) {
  29459. value = value / 255;
  29460. }
  29461. return value;
  29462. }
  29463. case VertexBuffer.SHORT: {
  29464. var value = dataView.getInt16(byteOffset, true);
  29465. if (normalized) {
  29466. value = Math.max(value / 16383, -1);
  29467. }
  29468. return value;
  29469. }
  29470. case VertexBuffer.UNSIGNED_SHORT: {
  29471. var value = dataView.getUint16(byteOffset, true);
  29472. if (normalized) {
  29473. value = value / 65535;
  29474. }
  29475. return value;
  29476. }
  29477. case VertexBuffer.FLOAT: {
  29478. return dataView.getFloat32(byteOffset, true);
  29479. }
  29480. default: {
  29481. throw new Error("Invalid component type " + type);
  29482. }
  29483. }
  29484. };
  29485. /**
  29486. * The byte type.
  29487. */
  29488. VertexBuffer.BYTE = 5120;
  29489. /**
  29490. * The unsigned byte type.
  29491. */
  29492. VertexBuffer.UNSIGNED_BYTE = 5121;
  29493. /**
  29494. * The short type.
  29495. */
  29496. VertexBuffer.SHORT = 5122;
  29497. /**
  29498. * The unsigned short type.
  29499. */
  29500. VertexBuffer.UNSIGNED_SHORT = 5123;
  29501. /**
  29502. * The integer type.
  29503. */
  29504. VertexBuffer.INT = 5124;
  29505. /**
  29506. * The unsigned integer type.
  29507. */
  29508. VertexBuffer.UNSIGNED_INT = 5125;
  29509. /**
  29510. * The float type.
  29511. */
  29512. VertexBuffer.FLOAT = 5126;
  29513. // Enums
  29514. VertexBuffer._PositionKind = "position";
  29515. VertexBuffer._NormalKind = "normal";
  29516. VertexBuffer._TangentKind = "tangent";
  29517. VertexBuffer._UVKind = "uv";
  29518. VertexBuffer._UV2Kind = "uv2";
  29519. VertexBuffer._UV3Kind = "uv3";
  29520. VertexBuffer._UV4Kind = "uv4";
  29521. VertexBuffer._UV5Kind = "uv5";
  29522. VertexBuffer._UV6Kind = "uv6";
  29523. VertexBuffer._ColorKind = "color";
  29524. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29525. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29526. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29527. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29528. return VertexBuffer;
  29529. }());
  29530. BABYLON.VertexBuffer = VertexBuffer;
  29531. })(BABYLON || (BABYLON = {}));
  29532. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29533. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29534. var BABYLON;
  29535. (function (BABYLON) {
  29536. /**
  29537. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29538. */
  29539. var DummyInternalTextureTracker = /** @class */ (function () {
  29540. function DummyInternalTextureTracker() {
  29541. /**
  29542. * Gets or set the previous tracker in the list
  29543. */
  29544. this.previous = null;
  29545. /**
  29546. * Gets or set the next tracker in the list
  29547. */
  29548. this.next = null;
  29549. }
  29550. return DummyInternalTextureTracker;
  29551. }());
  29552. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29553. })(BABYLON || (BABYLON = {}));
  29554. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29555. var BABYLON;
  29556. (function (BABYLON) {
  29557. /**
  29558. * Class used to store data associated with WebGL texture data for the engine
  29559. * This class should not be used directly
  29560. */
  29561. var InternalTexture = /** @class */ (function () {
  29562. /**
  29563. * Creates a new InternalTexture
  29564. * @param engine defines the engine to use
  29565. * @param dataSource defines the type of data that will be used
  29566. */
  29567. function InternalTexture(engine, dataSource) {
  29568. /**
  29569. * Observable called when the texture is loaded
  29570. */
  29571. this.onLoadedObservable = new BABYLON.Observable();
  29572. /**
  29573. * Gets or set the previous tracker in the list
  29574. */
  29575. this.previous = null;
  29576. /**
  29577. * Gets or set the next tracker in the list
  29578. */
  29579. this.next = null;
  29580. // Private
  29581. /** @hidden */
  29582. this._initialSlot = -1;
  29583. /** @hidden */
  29584. this._designatedSlot = -1;
  29585. /** @hidden */
  29586. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29587. /** @hidden */
  29588. this._comparisonFunction = 0;
  29589. /** @hidden */
  29590. this._sphericalPolynomial = null;
  29591. /** @hidden */
  29592. this._lodGenerationScale = 0;
  29593. /** @hidden */
  29594. this._lodGenerationOffset = 0;
  29595. /** @hidden */
  29596. this._isRGBD = false;
  29597. /** @hidden */
  29598. this._references = 1;
  29599. this._engine = engine;
  29600. this._dataSource = dataSource;
  29601. this._webGLTexture = engine._createTexture();
  29602. }
  29603. /**
  29604. * Gets the Engine the texture belongs to.
  29605. * @returns The babylon engine
  29606. */
  29607. InternalTexture.prototype.getEngine = function () {
  29608. return this._engine;
  29609. };
  29610. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29611. /**
  29612. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29613. */
  29614. get: function () {
  29615. return this._dataSource;
  29616. },
  29617. enumerable: true,
  29618. configurable: true
  29619. });
  29620. /**
  29621. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29622. */
  29623. InternalTexture.prototype.incrementReferences = function () {
  29624. this._references++;
  29625. };
  29626. /**
  29627. * Change the size of the texture (not the size of the content)
  29628. * @param width defines the new width
  29629. * @param height defines the new height
  29630. * @param depth defines the new depth (1 by default)
  29631. */
  29632. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29633. if (depth === void 0) { depth = 1; }
  29634. this.width = width;
  29635. this.height = height;
  29636. this.depth = depth;
  29637. this.baseWidth = width;
  29638. this.baseHeight = height;
  29639. this.baseDepth = depth;
  29640. this._size = width * height * depth;
  29641. };
  29642. /** @hidden */
  29643. InternalTexture.prototype._rebuild = function () {
  29644. var _this = this;
  29645. var proxy;
  29646. this.isReady = false;
  29647. this._cachedCoordinatesMode = null;
  29648. this._cachedWrapU = null;
  29649. this._cachedWrapV = null;
  29650. this._cachedAnisotropicFilteringLevel = null;
  29651. switch (this._dataSource) {
  29652. case InternalTexture.DATASOURCE_TEMP:
  29653. return;
  29654. case InternalTexture.DATASOURCE_URL:
  29655. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29656. _this.isReady = true;
  29657. }, null, this._buffer, undefined, this.format);
  29658. proxy._swapAndDie(this);
  29659. return;
  29660. case InternalTexture.DATASOURCE_RAW:
  29661. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29662. proxy._swapAndDie(this);
  29663. this.isReady = true;
  29664. return;
  29665. case InternalTexture.DATASOURCE_RAW3D:
  29666. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29667. proxy._swapAndDie(this);
  29668. this.isReady = true;
  29669. return;
  29670. case InternalTexture.DATASOURCE_DYNAMIC:
  29671. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29672. proxy._swapAndDie(this);
  29673. // The engine will make sure to update content so no need to flag it as isReady = true
  29674. return;
  29675. case InternalTexture.DATASOURCE_RENDERTARGET:
  29676. var options = new BABYLON.RenderTargetCreationOptions();
  29677. options.generateDepthBuffer = this._generateDepthBuffer;
  29678. options.generateMipMaps = this.generateMipMaps;
  29679. options.generateStencilBuffer = this._generateStencilBuffer;
  29680. options.samplingMode = this.samplingMode;
  29681. options.type = this.type;
  29682. if (this.isCube) {
  29683. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29684. }
  29685. else {
  29686. var size = {
  29687. width: this.width,
  29688. height: this.height
  29689. };
  29690. proxy = this._engine.createRenderTargetTexture(size, options);
  29691. }
  29692. proxy._swapAndDie(this);
  29693. this.isReady = true;
  29694. return;
  29695. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29696. var depthTextureOptions = {
  29697. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29698. comparisonFunction: this._comparisonFunction,
  29699. generateStencil: this._generateStencilBuffer,
  29700. isCube: this.isCube
  29701. };
  29702. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29703. proxy._swapAndDie(this);
  29704. this.isReady = true;
  29705. return;
  29706. case InternalTexture.DATASOURCE_CUBE:
  29707. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29708. _this.isReady = true;
  29709. }, null, this.format, this._extension);
  29710. proxy._swapAndDie(this);
  29711. return;
  29712. case InternalTexture.DATASOURCE_CUBERAW:
  29713. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29714. proxy._swapAndDie(this);
  29715. this.isReady = true;
  29716. return;
  29717. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29718. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29719. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29720. _this.isReady = true;
  29721. });
  29722. proxy._swapAndDie(this);
  29723. return;
  29724. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29725. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29726. if (proxy) {
  29727. proxy._swapAndDie(_this);
  29728. }
  29729. _this.isReady = true;
  29730. }, null, this.format, this._extension);
  29731. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29732. return;
  29733. }
  29734. };
  29735. InternalTexture.prototype._swapAndDie = function (target) {
  29736. target._webGLTexture = this._webGLTexture;
  29737. if (this._framebuffer) {
  29738. target._framebuffer = this._framebuffer;
  29739. }
  29740. if (this._depthStencilBuffer) {
  29741. target._depthStencilBuffer = this._depthStencilBuffer;
  29742. }
  29743. if (this._lodTextureHigh) {
  29744. if (target._lodTextureHigh) {
  29745. target._lodTextureHigh.dispose();
  29746. }
  29747. target._lodTextureHigh = this._lodTextureHigh;
  29748. }
  29749. if (this._lodTextureMid) {
  29750. if (target._lodTextureMid) {
  29751. target._lodTextureMid.dispose();
  29752. }
  29753. target._lodTextureMid = this._lodTextureMid;
  29754. }
  29755. if (this._lodTextureLow) {
  29756. if (target._lodTextureLow) {
  29757. target._lodTextureLow.dispose();
  29758. }
  29759. target._lodTextureLow = this._lodTextureLow;
  29760. }
  29761. var cache = this._engine.getLoadedTexturesCache();
  29762. var index = cache.indexOf(this);
  29763. if (index !== -1) {
  29764. cache.splice(index, 1);
  29765. }
  29766. };
  29767. /**
  29768. * Dispose the current allocated resources
  29769. */
  29770. InternalTexture.prototype.dispose = function () {
  29771. if (!this._webGLTexture) {
  29772. return;
  29773. }
  29774. this._references--;
  29775. if (this._references === 0) {
  29776. this._engine._releaseTexture(this);
  29777. this._webGLTexture = null;
  29778. this.previous = null;
  29779. this.next = null;
  29780. }
  29781. };
  29782. /**
  29783. * The source of the texture data is unknown
  29784. */
  29785. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29786. /**
  29787. * Texture data comes from an URL
  29788. */
  29789. InternalTexture.DATASOURCE_URL = 1;
  29790. /**
  29791. * Texture data is only used for temporary storage
  29792. */
  29793. InternalTexture.DATASOURCE_TEMP = 2;
  29794. /**
  29795. * Texture data comes from raw data (ArrayBuffer)
  29796. */
  29797. InternalTexture.DATASOURCE_RAW = 3;
  29798. /**
  29799. * Texture content is dynamic (video or dynamic texture)
  29800. */
  29801. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29802. /**
  29803. * Texture content is generated by rendering to it
  29804. */
  29805. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29806. /**
  29807. * Texture content is part of a multi render target process
  29808. */
  29809. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29810. /**
  29811. * Texture data comes from a cube data file
  29812. */
  29813. InternalTexture.DATASOURCE_CUBE = 7;
  29814. /**
  29815. * Texture data comes from a raw cube data
  29816. */
  29817. InternalTexture.DATASOURCE_CUBERAW = 8;
  29818. /**
  29819. * Texture data come from a prefiltered cube data file
  29820. */
  29821. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29822. /**
  29823. * Texture content is raw 3D data
  29824. */
  29825. InternalTexture.DATASOURCE_RAW3D = 10;
  29826. /**
  29827. * Texture content is a depth texture
  29828. */
  29829. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29830. /**
  29831. * Texture data comes from a raw cube data encoded with RGBD
  29832. */
  29833. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29834. return InternalTexture;
  29835. }());
  29836. BABYLON.InternalTexture = InternalTexture;
  29837. })(BABYLON || (BABYLON = {}));
  29838. //# sourceMappingURL=babylon.internalTexture.js.map
  29839. var BABYLON;
  29840. (function (BABYLON) {
  29841. var BaseTexture = /** @class */ (function () {
  29842. function BaseTexture(scene) {
  29843. this._hasAlpha = false;
  29844. this.getAlphaFromRGB = false;
  29845. this.level = 1;
  29846. this.coordinatesIndex = 0;
  29847. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29848. /**
  29849. * | Value | Type | Description |
  29850. * | ----- | ------------------ | ----------- |
  29851. * | 0 | CLAMP_ADDRESSMODE | |
  29852. * | 1 | WRAP_ADDRESSMODE | |
  29853. * | 2 | MIRROR_ADDRESSMODE | |
  29854. */
  29855. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29856. /**
  29857. * | Value | Type | Description |
  29858. * | ----- | ------------------ | ----------- |
  29859. * | 0 | CLAMP_ADDRESSMODE | |
  29860. * | 1 | WRAP_ADDRESSMODE | |
  29861. * | 2 | MIRROR_ADDRESSMODE | |
  29862. */
  29863. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29864. /**
  29865. * | Value | Type | Description |
  29866. * | ----- | ------------------ | ----------- |
  29867. * | 0 | CLAMP_ADDRESSMODE | |
  29868. * | 1 | WRAP_ADDRESSMODE | |
  29869. * | 2 | MIRROR_ADDRESSMODE | |
  29870. */
  29871. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29872. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29873. this.isCube = false;
  29874. this.is3D = false;
  29875. this.gammaSpace = true;
  29876. this.invertZ = false;
  29877. this.lodLevelInAlpha = false;
  29878. this.isRenderTarget = false;
  29879. this.animations = new Array();
  29880. /**
  29881. * An event triggered when the texture is disposed.
  29882. */
  29883. this.onDisposeObservable = new BABYLON.Observable();
  29884. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29885. this._cachedSize = BABYLON.Size.Zero();
  29886. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29887. if (this._scene) {
  29888. this._scene.textures.push(this);
  29889. }
  29890. this._uid = null;
  29891. }
  29892. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29893. get: function () {
  29894. return this._hasAlpha;
  29895. },
  29896. set: function (value) {
  29897. if (this._hasAlpha === value) {
  29898. return;
  29899. }
  29900. this._hasAlpha = value;
  29901. if (this._scene) {
  29902. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29903. }
  29904. },
  29905. enumerable: true,
  29906. configurable: true
  29907. });
  29908. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29909. get: function () {
  29910. return this._coordinatesMode;
  29911. },
  29912. /**
  29913. * How a texture is mapped.
  29914. *
  29915. * | Value | Type | Description |
  29916. * | ----- | ----------------------------------- | ----------- |
  29917. * | 0 | EXPLICIT_MODE | |
  29918. * | 1 | SPHERICAL_MODE | |
  29919. * | 2 | PLANAR_MODE | |
  29920. * | 3 | CUBIC_MODE | |
  29921. * | 4 | PROJECTION_MODE | |
  29922. * | 5 | SKYBOX_MODE | |
  29923. * | 6 | INVCUBIC_MODE | |
  29924. * | 7 | EQUIRECTANGULAR_MODE | |
  29925. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29926. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29927. */
  29928. set: function (value) {
  29929. if (this._coordinatesMode === value) {
  29930. return;
  29931. }
  29932. this._coordinatesMode = value;
  29933. if (this._scene) {
  29934. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29935. }
  29936. },
  29937. enumerable: true,
  29938. configurable: true
  29939. });
  29940. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29941. /**
  29942. * Gets whether or not the texture contains RGBD data.
  29943. */
  29944. get: function () {
  29945. return this._texture != null && this._texture._isRGBD;
  29946. },
  29947. enumerable: true,
  29948. configurable: true
  29949. });
  29950. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29951. get: function () {
  29952. if (this._texture)
  29953. return this._texture._lodGenerationOffset;
  29954. return 0.0;
  29955. },
  29956. set: function (value) {
  29957. if (this._texture)
  29958. this._texture._lodGenerationOffset = value;
  29959. },
  29960. enumerable: true,
  29961. configurable: true
  29962. });
  29963. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29964. get: function () {
  29965. if (this._texture)
  29966. return this._texture._lodGenerationScale;
  29967. return 0.0;
  29968. },
  29969. set: function (value) {
  29970. if (this._texture)
  29971. this._texture._lodGenerationScale = value;
  29972. },
  29973. enumerable: true,
  29974. configurable: true
  29975. });
  29976. Object.defineProperty(BaseTexture.prototype, "uid", {
  29977. get: function () {
  29978. if (!this._uid) {
  29979. this._uid = BABYLON.Tools.RandomId();
  29980. }
  29981. return this._uid;
  29982. },
  29983. enumerable: true,
  29984. configurable: true
  29985. });
  29986. BaseTexture.prototype.toString = function () {
  29987. return this.name;
  29988. };
  29989. BaseTexture.prototype.getClassName = function () {
  29990. return "BaseTexture";
  29991. };
  29992. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29993. set: function (callback) {
  29994. if (this._onDisposeObserver) {
  29995. this.onDisposeObservable.remove(this._onDisposeObserver);
  29996. }
  29997. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29998. },
  29999. enumerable: true,
  30000. configurable: true
  30001. });
  30002. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30003. get: function () {
  30004. return true;
  30005. },
  30006. enumerable: true,
  30007. configurable: true
  30008. });
  30009. BaseTexture.prototype.getScene = function () {
  30010. return this._scene;
  30011. };
  30012. BaseTexture.prototype.getTextureMatrix = function () {
  30013. return BABYLON.Matrix.IdentityReadOnly;
  30014. };
  30015. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30016. return BABYLON.Matrix.IdentityReadOnly;
  30017. };
  30018. BaseTexture.prototype.getInternalTexture = function () {
  30019. return this._texture;
  30020. };
  30021. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30022. return !this.isBlocking || this.isReady();
  30023. };
  30024. BaseTexture.prototype.isReady = function () {
  30025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30026. this.delayLoad();
  30027. return false;
  30028. }
  30029. if (this._texture) {
  30030. return this._texture.isReady;
  30031. }
  30032. return false;
  30033. };
  30034. BaseTexture.prototype.getSize = function () {
  30035. if (this._texture) {
  30036. if (this._texture.width) {
  30037. this._cachedSize.width = this._texture.width;
  30038. this._cachedSize.height = this._texture.height;
  30039. return this._cachedSize;
  30040. }
  30041. if (this._texture._size) {
  30042. this._cachedSize.width = this._texture._size;
  30043. this._cachedSize.height = this._texture._size;
  30044. return this._cachedSize;
  30045. }
  30046. }
  30047. return this._cachedSize;
  30048. };
  30049. BaseTexture.prototype.getBaseSize = function () {
  30050. if (!this.isReady() || !this._texture)
  30051. return BABYLON.Size.Zero();
  30052. if (this._texture._size) {
  30053. return new BABYLON.Size(this._texture._size, this._texture._size);
  30054. }
  30055. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30056. };
  30057. BaseTexture.prototype.scale = function (ratio) {
  30058. };
  30059. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30060. get: function () {
  30061. return false;
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30067. if (!this._scene) {
  30068. return null;
  30069. }
  30070. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30071. for (var index = 0; index < texturesCache.length; index++) {
  30072. var texturesCacheEntry = texturesCache[index];
  30073. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30074. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30075. texturesCacheEntry.incrementReferences();
  30076. return texturesCacheEntry;
  30077. }
  30078. }
  30079. }
  30080. return null;
  30081. };
  30082. BaseTexture.prototype._rebuild = function () {
  30083. };
  30084. BaseTexture.prototype.delayLoad = function () {
  30085. };
  30086. BaseTexture.prototype.clone = function () {
  30087. return null;
  30088. };
  30089. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30090. get: function () {
  30091. if (!this._texture) {
  30092. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30093. }
  30094. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30095. },
  30096. enumerable: true,
  30097. configurable: true
  30098. });
  30099. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30100. get: function () {
  30101. if (!this._texture) {
  30102. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30103. }
  30104. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. /**
  30110. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30111. * This will returns an RGBA array buffer containing either in values (0-255) or
  30112. * float values (0-1) depending of the underlying buffer type.
  30113. * @param faceIndex The face of the texture to read (in case of cube texture)
  30114. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30115. * @returns The Array buffer containing the pixels data.
  30116. */
  30117. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30118. if (faceIndex === void 0) { faceIndex = 0; }
  30119. if (level === void 0) { level = 0; }
  30120. if (!this._texture) {
  30121. return null;
  30122. }
  30123. var size = this.getSize();
  30124. var width = size.width;
  30125. var height = size.height;
  30126. var scene = this.getScene();
  30127. if (!scene) {
  30128. return null;
  30129. }
  30130. var engine = scene.getEngine();
  30131. if (level != 0) {
  30132. width = width / Math.pow(2, level);
  30133. height = height / Math.pow(2, level);
  30134. width = Math.round(width);
  30135. height = Math.round(height);
  30136. }
  30137. if (this._texture.isCube) {
  30138. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30139. }
  30140. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30141. };
  30142. BaseTexture.prototype.releaseInternalTexture = function () {
  30143. if (this._texture) {
  30144. this._texture.dispose();
  30145. this._texture = null;
  30146. }
  30147. };
  30148. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30149. get: function () {
  30150. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30151. return null;
  30152. }
  30153. if (!this._texture._sphericalPolynomial) {
  30154. this._texture._sphericalPolynomial =
  30155. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30156. }
  30157. return this._texture._sphericalPolynomial;
  30158. },
  30159. set: function (value) {
  30160. if (this._texture) {
  30161. this._texture._sphericalPolynomial = value;
  30162. }
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30168. get: function () {
  30169. if (this._texture) {
  30170. return this._texture._lodTextureHigh;
  30171. }
  30172. return null;
  30173. },
  30174. enumerable: true,
  30175. configurable: true
  30176. });
  30177. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30178. get: function () {
  30179. if (this._texture) {
  30180. return this._texture._lodTextureMid;
  30181. }
  30182. return null;
  30183. },
  30184. enumerable: true,
  30185. configurable: true
  30186. });
  30187. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30188. get: function () {
  30189. if (this._texture) {
  30190. return this._texture._lodTextureLow;
  30191. }
  30192. return null;
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. BaseTexture.prototype.dispose = function () {
  30198. if (!this._scene) {
  30199. return;
  30200. }
  30201. // Animations
  30202. this._scene.stopAnimation(this);
  30203. // Remove from scene
  30204. this._scene._removePendingData(this);
  30205. var index = this._scene.textures.indexOf(this);
  30206. if (index >= 0) {
  30207. this._scene.textures.splice(index, 1);
  30208. }
  30209. if (this._texture === undefined) {
  30210. return;
  30211. }
  30212. // Release
  30213. this.releaseInternalTexture();
  30214. // Callback
  30215. this.onDisposeObservable.notifyObservers(this);
  30216. this.onDisposeObservable.clear();
  30217. };
  30218. BaseTexture.prototype.serialize = function () {
  30219. if (!this.name) {
  30220. return null;
  30221. }
  30222. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30223. // Animations
  30224. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30225. return serializationObject;
  30226. };
  30227. BaseTexture.WhenAllReady = function (textures, callback) {
  30228. var numRemaining = textures.length;
  30229. if (numRemaining === 0) {
  30230. callback();
  30231. return;
  30232. }
  30233. var _loop_1 = function () {
  30234. texture = textures[i];
  30235. if (texture.isReady()) {
  30236. if (--numRemaining === 0) {
  30237. callback();
  30238. }
  30239. }
  30240. else {
  30241. onLoadObservable = texture.onLoadObservable;
  30242. var onLoadCallback_1 = function () {
  30243. onLoadObservable.removeCallback(onLoadCallback_1);
  30244. if (--numRemaining === 0) {
  30245. callback();
  30246. }
  30247. };
  30248. onLoadObservable.add(onLoadCallback_1);
  30249. }
  30250. };
  30251. var texture, onLoadObservable;
  30252. for (var i = 0; i < textures.length; i++) {
  30253. _loop_1();
  30254. }
  30255. };
  30256. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30257. __decorate([
  30258. BABYLON.serialize()
  30259. ], BaseTexture.prototype, "name", void 0);
  30260. __decorate([
  30261. BABYLON.serialize("hasAlpha")
  30262. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30263. __decorate([
  30264. BABYLON.serialize()
  30265. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30266. __decorate([
  30267. BABYLON.serialize()
  30268. ], BaseTexture.prototype, "level", void 0);
  30269. __decorate([
  30270. BABYLON.serialize()
  30271. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30272. __decorate([
  30273. BABYLON.serialize("coordinatesMode")
  30274. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30275. __decorate([
  30276. BABYLON.serialize()
  30277. ], BaseTexture.prototype, "wrapU", void 0);
  30278. __decorate([
  30279. BABYLON.serialize()
  30280. ], BaseTexture.prototype, "wrapV", void 0);
  30281. __decorate([
  30282. BABYLON.serialize()
  30283. ], BaseTexture.prototype, "wrapR", void 0);
  30284. __decorate([
  30285. BABYLON.serialize()
  30286. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30287. __decorate([
  30288. BABYLON.serialize()
  30289. ], BaseTexture.prototype, "isCube", void 0);
  30290. __decorate([
  30291. BABYLON.serialize()
  30292. ], BaseTexture.prototype, "is3D", void 0);
  30293. __decorate([
  30294. BABYLON.serialize()
  30295. ], BaseTexture.prototype, "gammaSpace", void 0);
  30296. __decorate([
  30297. BABYLON.serialize()
  30298. ], BaseTexture.prototype, "invertZ", void 0);
  30299. __decorate([
  30300. BABYLON.serialize()
  30301. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30302. __decorate([
  30303. BABYLON.serialize()
  30304. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30305. __decorate([
  30306. BABYLON.serialize()
  30307. ], BaseTexture.prototype, "lodGenerationScale", null);
  30308. __decorate([
  30309. BABYLON.serialize()
  30310. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30311. return BaseTexture;
  30312. }());
  30313. BABYLON.BaseTexture = BaseTexture;
  30314. })(BABYLON || (BABYLON = {}));
  30315. //# sourceMappingURL=babylon.baseTexture.js.map
  30316. var BABYLON;
  30317. (function (BABYLON) {
  30318. var Texture = /** @class */ (function (_super) {
  30319. __extends(Texture, _super);
  30320. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30321. if (noMipmap === void 0) { noMipmap = false; }
  30322. if (invertY === void 0) { invertY = true; }
  30323. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30324. if (onLoad === void 0) { onLoad = null; }
  30325. if (onError === void 0) { onError = null; }
  30326. if (buffer === void 0) { buffer = null; }
  30327. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30328. var _this = _super.call(this, scene) || this;
  30329. _this.uOffset = 0;
  30330. _this.vOffset = 0;
  30331. _this.uScale = 1.0;
  30332. _this.vScale = 1.0;
  30333. _this.uAng = 0;
  30334. _this.vAng = 0;
  30335. _this.wAng = 0;
  30336. /**
  30337. * Defines the center of rotation (U)
  30338. */
  30339. _this.uRotationCenter = 0.5;
  30340. /**
  30341. * Defines the center of rotation (V)
  30342. */
  30343. _this.vRotationCenter = 0.5;
  30344. /**
  30345. * Defines the center of rotation (W)
  30346. */
  30347. _this.wRotationCenter = 0.5;
  30348. _this._isBlocking = true;
  30349. _this.name = url || "";
  30350. _this.url = url;
  30351. _this._noMipmap = noMipmap;
  30352. _this._invertY = invertY;
  30353. _this._samplingMode = samplingMode;
  30354. _this._buffer = buffer;
  30355. _this._deleteBuffer = deleteBuffer;
  30356. if (format) {
  30357. _this._format = format;
  30358. }
  30359. scene = _this.getScene();
  30360. if (!scene) {
  30361. return _this;
  30362. }
  30363. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30364. var load = function () {
  30365. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30366. _this.onLoadObservable.notifyObservers(_this);
  30367. }
  30368. if (onLoad) {
  30369. onLoad();
  30370. }
  30371. if (!_this.isBlocking && scene) {
  30372. scene.resetCachedMaterial();
  30373. }
  30374. };
  30375. if (!_this.url) {
  30376. _this._delayedOnLoad = load;
  30377. _this._delayedOnError = onError;
  30378. return _this;
  30379. }
  30380. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30381. if (!_this._texture) {
  30382. if (!scene.useDelayedTextureLoading) {
  30383. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30384. if (deleteBuffer) {
  30385. delete _this._buffer;
  30386. }
  30387. }
  30388. else {
  30389. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30390. _this._delayedOnLoad = load;
  30391. _this._delayedOnError = onError;
  30392. }
  30393. }
  30394. else {
  30395. if (_this._texture.isReady) {
  30396. BABYLON.Tools.SetImmediate(function () { return load(); });
  30397. }
  30398. else {
  30399. _this._texture.onLoadedObservable.add(load);
  30400. }
  30401. }
  30402. return _this;
  30403. }
  30404. Object.defineProperty(Texture.prototype, "noMipmap", {
  30405. get: function () {
  30406. return this._noMipmap;
  30407. },
  30408. enumerable: true,
  30409. configurable: true
  30410. });
  30411. Object.defineProperty(Texture.prototype, "isBlocking", {
  30412. get: function () {
  30413. return this._isBlocking;
  30414. },
  30415. set: function (value) {
  30416. this._isBlocking = value;
  30417. },
  30418. enumerable: true,
  30419. configurable: true
  30420. });
  30421. Object.defineProperty(Texture.prototype, "samplingMode", {
  30422. get: function () {
  30423. return this._samplingMode;
  30424. },
  30425. enumerable: true,
  30426. configurable: true
  30427. });
  30428. /**
  30429. * Update the url (and optional buffer) of this texture if url was null during construction.
  30430. * @param url the url of the texture
  30431. * @param buffer the buffer of the texture (defaults to null)
  30432. */
  30433. Texture.prototype.updateURL = function (url, buffer) {
  30434. if (buffer === void 0) { buffer = null; }
  30435. if (this.url) {
  30436. throw new Error("URL is already set");
  30437. }
  30438. this.url = url;
  30439. this._buffer = buffer;
  30440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30441. this.delayLoad();
  30442. };
  30443. Texture.prototype.delayLoad = function () {
  30444. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30445. return;
  30446. }
  30447. var scene = this.getScene();
  30448. if (!scene) {
  30449. return;
  30450. }
  30451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30452. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30453. if (!this._texture) {
  30454. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30455. if (this._deleteBuffer) {
  30456. delete this._buffer;
  30457. }
  30458. }
  30459. else {
  30460. if (this._delayedOnLoad) {
  30461. if (this._texture.isReady) {
  30462. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30463. }
  30464. else {
  30465. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30466. }
  30467. }
  30468. }
  30469. this._delayedOnLoad = null;
  30470. this._delayedOnError = null;
  30471. };
  30472. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30473. if (!this._texture) {
  30474. return;
  30475. }
  30476. var scene = this.getScene();
  30477. if (!scene) {
  30478. return;
  30479. }
  30480. this._samplingMode = samplingMode;
  30481. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30482. };
  30483. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30484. x *= this.uScale;
  30485. y *= this.vScale;
  30486. x -= this.uRotationCenter * this.uScale;
  30487. y -= this.vRotationCenter * this.vScale;
  30488. z -= this.wRotationCenter;
  30489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30490. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30491. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30492. t.z += this.wRotationCenter;
  30493. };
  30494. Texture.prototype.getTextureMatrix = function () {
  30495. var _this = this;
  30496. if (this.uOffset === this._cachedUOffset &&
  30497. this.vOffset === this._cachedVOffset &&
  30498. this.uScale === this._cachedUScale &&
  30499. this.vScale === this._cachedVScale &&
  30500. this.uAng === this._cachedUAng &&
  30501. this.vAng === this._cachedVAng &&
  30502. this.wAng === this._cachedWAng) {
  30503. return this._cachedTextureMatrix;
  30504. }
  30505. this._cachedUOffset = this.uOffset;
  30506. this._cachedVOffset = this.vOffset;
  30507. this._cachedUScale = this.uScale;
  30508. this._cachedVScale = this.vScale;
  30509. this._cachedUAng = this.uAng;
  30510. this._cachedVAng = this.vAng;
  30511. this._cachedWAng = this.wAng;
  30512. if (!this._cachedTextureMatrix) {
  30513. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30514. this._rowGenerationMatrix = new BABYLON.Matrix();
  30515. this._t0 = BABYLON.Vector3.Zero();
  30516. this._t1 = BABYLON.Vector3.Zero();
  30517. this._t2 = BABYLON.Vector3.Zero();
  30518. }
  30519. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30520. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30521. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30522. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30523. this._t1.subtractInPlace(this._t0);
  30524. this._t2.subtractInPlace(this._t0);
  30525. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30526. this._cachedTextureMatrix.m[0] = this._t1.x;
  30527. this._cachedTextureMatrix.m[1] = this._t1.y;
  30528. this._cachedTextureMatrix.m[2] = this._t1.z;
  30529. this._cachedTextureMatrix.m[4] = this._t2.x;
  30530. this._cachedTextureMatrix.m[5] = this._t2.y;
  30531. this._cachedTextureMatrix.m[6] = this._t2.z;
  30532. this._cachedTextureMatrix.m[8] = this._t0.x;
  30533. this._cachedTextureMatrix.m[9] = this._t0.y;
  30534. this._cachedTextureMatrix.m[10] = this._t0.z;
  30535. var scene = this.getScene();
  30536. if (!scene) {
  30537. return this._cachedTextureMatrix;
  30538. }
  30539. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30540. return mat.hasTexture(_this);
  30541. });
  30542. return this._cachedTextureMatrix;
  30543. };
  30544. Texture.prototype.getReflectionTextureMatrix = function () {
  30545. var _this = this;
  30546. var scene = this.getScene();
  30547. if (!scene) {
  30548. return this._cachedTextureMatrix;
  30549. }
  30550. if (this.uOffset === this._cachedUOffset &&
  30551. this.vOffset === this._cachedVOffset &&
  30552. this.uScale === this._cachedUScale &&
  30553. this.vScale === this._cachedVScale &&
  30554. this.coordinatesMode === this._cachedCoordinatesMode) {
  30555. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30556. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30557. return this._cachedTextureMatrix;
  30558. }
  30559. }
  30560. else {
  30561. return this._cachedTextureMatrix;
  30562. }
  30563. }
  30564. if (!this._cachedTextureMatrix) {
  30565. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30566. }
  30567. if (!this._projectionModeMatrix) {
  30568. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30569. }
  30570. this._cachedUOffset = this.uOffset;
  30571. this._cachedVOffset = this.vOffset;
  30572. this._cachedUScale = this.uScale;
  30573. this._cachedVScale = this.vScale;
  30574. this._cachedCoordinatesMode = this.coordinatesMode;
  30575. switch (this.coordinatesMode) {
  30576. case Texture.PLANAR_MODE:
  30577. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30578. this._cachedTextureMatrix[0] = this.uScale;
  30579. this._cachedTextureMatrix[5] = this.vScale;
  30580. this._cachedTextureMatrix[12] = this.uOffset;
  30581. this._cachedTextureMatrix[13] = this.vOffset;
  30582. break;
  30583. case Texture.PROJECTION_MODE:
  30584. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30585. this._projectionModeMatrix.m[0] = 0.5;
  30586. this._projectionModeMatrix.m[5] = -0.5;
  30587. this._projectionModeMatrix.m[10] = 0.0;
  30588. this._projectionModeMatrix.m[12] = 0.5;
  30589. this._projectionModeMatrix.m[13] = 0.5;
  30590. this._projectionModeMatrix.m[14] = 1.0;
  30591. this._projectionModeMatrix.m[15] = 1.0;
  30592. var projectionMatrix = scene.getProjectionMatrix();
  30593. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30594. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30595. break;
  30596. default:
  30597. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30598. break;
  30599. }
  30600. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30601. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30602. });
  30603. return this._cachedTextureMatrix;
  30604. };
  30605. Texture.prototype.clone = function () {
  30606. var _this = this;
  30607. return BABYLON.SerializationHelper.Clone(function () {
  30608. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30609. }, this);
  30610. };
  30611. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30612. get: function () {
  30613. if (!this._onLoadObservable) {
  30614. this._onLoadObservable = new BABYLON.Observable();
  30615. }
  30616. return this._onLoadObservable;
  30617. },
  30618. enumerable: true,
  30619. configurable: true
  30620. });
  30621. Texture.prototype.serialize = function () {
  30622. var serializationObject = _super.prototype.serialize.call(this);
  30623. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30624. serializationObject.base64String = this._buffer;
  30625. serializationObject.name = serializationObject.name.replace("data:", "");
  30626. }
  30627. serializationObject.invertY = this._invertY;
  30628. serializationObject.samplingMode = this.samplingMode;
  30629. return serializationObject;
  30630. };
  30631. Texture.prototype.getClassName = function () {
  30632. return "Texture";
  30633. };
  30634. Texture.prototype.dispose = function () {
  30635. _super.prototype.dispose.call(this);
  30636. if (this._onLoadObservable) {
  30637. this._onLoadObservable.clear();
  30638. this._onLoadObservable = null;
  30639. }
  30640. this._delayedOnLoad = null;
  30641. this._delayedOnError = null;
  30642. };
  30643. // Statics
  30644. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30645. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30646. if (onLoad === void 0) { onLoad = null; }
  30647. if (onError === void 0) { onError = null; }
  30648. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30649. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30650. };
  30651. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30652. if (parsedTexture.customType) {
  30653. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30654. // Update Sampling Mode
  30655. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30656. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30657. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30658. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30659. }
  30660. }
  30661. return parsedCustomTexture;
  30662. }
  30663. if (parsedTexture.isCube) {
  30664. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30665. }
  30666. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30667. return null;
  30668. }
  30669. var texture = BABYLON.SerializationHelper.Parse(function () {
  30670. var generateMipMaps = true;
  30671. if (parsedTexture.noMipmap) {
  30672. generateMipMaps = false;
  30673. }
  30674. if (parsedTexture.mirrorPlane) {
  30675. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30676. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30677. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30678. return mirrorTexture;
  30679. }
  30680. else if (parsedTexture.isRenderTarget) {
  30681. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30682. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30683. return renderTargetTexture;
  30684. }
  30685. else {
  30686. var texture;
  30687. if (parsedTexture.base64String) {
  30688. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30689. }
  30690. else {
  30691. var url = rootUrl + parsedTexture.name;
  30692. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30693. url = parsedTexture.url;
  30694. }
  30695. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30696. }
  30697. return texture;
  30698. }
  30699. }, parsedTexture, scene);
  30700. // Update Sampling Mode
  30701. if (parsedTexture.samplingMode) {
  30702. var sampling = parsedTexture.samplingMode;
  30703. if (texture._samplingMode !== sampling) {
  30704. texture.updateSamplingMode(sampling);
  30705. }
  30706. }
  30707. // Animations
  30708. if (parsedTexture.animations) {
  30709. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30710. var parsedAnimation = parsedTexture.animations[animationIndex];
  30711. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30712. }
  30713. }
  30714. return texture;
  30715. };
  30716. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30717. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30718. if (noMipmap === void 0) { noMipmap = false; }
  30719. if (invertY === void 0) { invertY = true; }
  30720. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30721. if (onLoad === void 0) { onLoad = null; }
  30722. if (onError === void 0) { onError = null; }
  30723. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30724. if (name.substr(0, 5) !== "data:") {
  30725. name = "data:" + name;
  30726. }
  30727. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30728. };
  30729. // Constants
  30730. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30731. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30732. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30733. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30734. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30735. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30736. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30737. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30738. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30739. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30740. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30741. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30742. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30743. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30744. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30745. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30746. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30747. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30748. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30749. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30750. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30751. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30752. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30753. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30754. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30755. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30756. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30757. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30758. /**
  30759. * 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
  30760. */
  30761. Texture.UseSerializedUrlIfAny = false;
  30762. __decorate([
  30763. BABYLON.serialize()
  30764. ], Texture.prototype, "url", void 0);
  30765. __decorate([
  30766. BABYLON.serialize()
  30767. ], Texture.prototype, "uOffset", void 0);
  30768. __decorate([
  30769. BABYLON.serialize()
  30770. ], Texture.prototype, "vOffset", void 0);
  30771. __decorate([
  30772. BABYLON.serialize()
  30773. ], Texture.prototype, "uScale", void 0);
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], Texture.prototype, "vScale", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], Texture.prototype, "uAng", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], Texture.prototype, "vAng", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], Texture.prototype, "wAng", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], Texture.prototype, "uRotationCenter", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], Texture.prototype, "vRotationCenter", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], Texture.prototype, "wRotationCenter", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], Texture.prototype, "isBlocking", null);
  30798. return Texture;
  30799. }(BABYLON.BaseTexture));
  30800. BABYLON.Texture = Texture;
  30801. })(BABYLON || (BABYLON = {}));
  30802. //# sourceMappingURL=babylon.texture.js.map
  30803. var BABYLON;
  30804. (function (BABYLON) {
  30805. /**
  30806. * @hidden
  30807. **/
  30808. var _InstancesBatch = /** @class */ (function () {
  30809. function _InstancesBatch() {
  30810. this.mustReturn = false;
  30811. this.visibleInstances = new Array();
  30812. this.renderSelf = new Array();
  30813. }
  30814. return _InstancesBatch;
  30815. }());
  30816. BABYLON._InstancesBatch = _InstancesBatch;
  30817. var Mesh = /** @class */ (function (_super) {
  30818. __extends(Mesh, _super);
  30819. /**
  30820. * @constructor
  30821. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30822. * @param {Scene} scene The scene to add this mesh to.
  30823. * @param {Node} parent The parent of this mesh, if it has one
  30824. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30825. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30826. * When false, achieved by calling a clone(), also passing False.
  30827. * This will make creation of children, recursive.
  30828. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30829. */
  30830. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30831. if (scene === void 0) { scene = null; }
  30832. if (parent === void 0) { parent = null; }
  30833. if (source === void 0) { source = null; }
  30834. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30835. var _this = _super.call(this, name, scene) || this;
  30836. // Events
  30837. /**
  30838. * An event triggered before rendering the mesh
  30839. */
  30840. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30841. /**
  30842. * An event triggered after rendering the mesh
  30843. */
  30844. _this.onAfterRenderObservable = new BABYLON.Observable();
  30845. /**
  30846. * An event triggered before drawing the mesh
  30847. */
  30848. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30849. // Members
  30850. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30851. _this.instances = new Array();
  30852. _this._LODLevels = new Array();
  30853. _this._visibleInstances = {};
  30854. _this._renderIdForInstances = new Array();
  30855. _this._batchCache = new _InstancesBatch();
  30856. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30857. // Use by builder only to know what orientation were the mesh build in.
  30858. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30859. _this.overrideMaterialSideOrientation = null;
  30860. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30861. // Will be used to save a source mesh reference, If any
  30862. _this._source = null;
  30863. scene = _this.getScene();
  30864. if (source) {
  30865. // Geometry
  30866. if (source._geometry) {
  30867. source._geometry.applyToMesh(_this);
  30868. }
  30869. // Deep copy
  30870. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30871. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  30872. // Source mesh
  30873. _this._source = source;
  30874. // Metadata
  30875. if (source.metadata && source.metadata.clone) {
  30876. _this.metadata = source.metadata.clone();
  30877. }
  30878. else {
  30879. _this.metadata = source.metadata;
  30880. }
  30881. // Tags
  30882. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30883. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30884. }
  30885. // Parent
  30886. _this.parent = source.parent;
  30887. // Pivot
  30888. _this.setPivotMatrix(source.getPivotMatrix());
  30889. _this.id = name + "." + source.id;
  30890. // Material
  30891. _this.material = source.material;
  30892. var index;
  30893. if (!doNotCloneChildren) {
  30894. // Children
  30895. var directDescendants = source.getDescendants(true);
  30896. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30897. var child = directDescendants[index_1];
  30898. if (child.clone) {
  30899. child.clone(name + "." + child.name, _this);
  30900. }
  30901. }
  30902. }
  30903. // Physics clone
  30904. var physicsEngine = _this.getScene().getPhysicsEngine();
  30905. if (clonePhysicsImpostor && physicsEngine) {
  30906. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30907. if (impostor) {
  30908. _this.physicsImpostor = impostor.clone(_this);
  30909. }
  30910. }
  30911. // Particles
  30912. for (index = 0; index < scene.particleSystems.length; index++) {
  30913. var system = scene.particleSystems[index];
  30914. if (system.emitter === source) {
  30915. system.clone(system.name, _this);
  30916. }
  30917. }
  30918. _this.refreshBoundingInfo();
  30919. _this.computeWorldMatrix(true);
  30920. }
  30921. // Parent
  30922. if (parent !== null) {
  30923. _this.parent = parent;
  30924. }
  30925. return _this;
  30926. }
  30927. Object.defineProperty(Mesh, "FRONTSIDE", {
  30928. /**
  30929. * Mesh side orientation : usually the external or front surface
  30930. */
  30931. get: function () {
  30932. return Mesh._FRONTSIDE;
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. Object.defineProperty(Mesh, "BACKSIDE", {
  30938. /**
  30939. * Mesh side orientation : usually the internal or back surface
  30940. */
  30941. get: function () {
  30942. return Mesh._BACKSIDE;
  30943. },
  30944. enumerable: true,
  30945. configurable: true
  30946. });
  30947. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30948. /**
  30949. * Mesh side orientation : both internal and external or front and back surfaces
  30950. */
  30951. get: function () {
  30952. return Mesh._DOUBLESIDE;
  30953. },
  30954. enumerable: true,
  30955. configurable: true
  30956. });
  30957. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30958. /**
  30959. * Mesh side orientation : by default, `FRONTSIDE`
  30960. */
  30961. get: function () {
  30962. return Mesh._DEFAULTSIDE;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(Mesh, "NO_CAP", {
  30968. /**
  30969. * Mesh cap setting : no cap
  30970. */
  30971. get: function () {
  30972. return Mesh._NO_CAP;
  30973. },
  30974. enumerable: true,
  30975. configurable: true
  30976. });
  30977. Object.defineProperty(Mesh, "CAP_START", {
  30978. /**
  30979. * Mesh cap setting : one cap at the beginning of the mesh
  30980. */
  30981. get: function () {
  30982. return Mesh._CAP_START;
  30983. },
  30984. enumerable: true,
  30985. configurable: true
  30986. });
  30987. Object.defineProperty(Mesh, "CAP_END", {
  30988. /**
  30989. * Mesh cap setting : one cap at the end of the mesh
  30990. */
  30991. get: function () {
  30992. return Mesh._CAP_END;
  30993. },
  30994. enumerable: true,
  30995. configurable: true
  30996. });
  30997. Object.defineProperty(Mesh, "CAP_ALL", {
  30998. /**
  30999. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31000. */
  31001. get: function () {
  31002. return Mesh._CAP_ALL;
  31003. },
  31004. enumerable: true,
  31005. configurable: true
  31006. });
  31007. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31008. set: function (callback) {
  31009. if (this._onBeforeDrawObserver) {
  31010. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31011. }
  31012. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31013. },
  31014. enumerable: true,
  31015. configurable: true
  31016. });
  31017. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31018. get: function () {
  31019. return this._morphTargetManager;
  31020. },
  31021. set: function (value) {
  31022. if (this._morphTargetManager === value) {
  31023. return;
  31024. }
  31025. this._morphTargetManager = value;
  31026. this._syncGeometryWithMorphTargetManager();
  31027. },
  31028. enumerable: true,
  31029. configurable: true
  31030. });
  31031. Object.defineProperty(Mesh.prototype, "source", {
  31032. get: function () {
  31033. return this._source;
  31034. },
  31035. enumerable: true,
  31036. configurable: true
  31037. });
  31038. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31039. get: function () {
  31040. return this._unIndexed;
  31041. },
  31042. set: function (value) {
  31043. if (this._unIndexed !== value) {
  31044. this._unIndexed = value;
  31045. this._markSubMeshesAsAttributesDirty();
  31046. }
  31047. },
  31048. enumerable: true,
  31049. configurable: true
  31050. });
  31051. // Methods
  31052. /**
  31053. * Returns the string "Mesh".
  31054. */
  31055. Mesh.prototype.getClassName = function () {
  31056. return "Mesh";
  31057. };
  31058. /**
  31059. * Returns a string.
  31060. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31061. */
  31062. Mesh.prototype.toString = function (fullDetails) {
  31063. var ret = _super.prototype.toString.call(this, fullDetails);
  31064. ret += ", n vertices: " + this.getTotalVertices();
  31065. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31066. if (this.animations) {
  31067. for (var i = 0; i < this.animations.length; i++) {
  31068. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31069. }
  31070. }
  31071. if (fullDetails) {
  31072. if (this._geometry) {
  31073. var ib = this.getIndices();
  31074. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31075. if (vb && ib) {
  31076. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31077. }
  31078. }
  31079. else {
  31080. ret += ", flat shading: UNKNOWN";
  31081. }
  31082. }
  31083. return ret;
  31084. };
  31085. Mesh.prototype._unBindEffect = function () {
  31086. _super.prototype._unBindEffect.call(this);
  31087. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31088. var instance = _a[_i];
  31089. instance._unBindEffect();
  31090. }
  31091. };
  31092. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31093. /**
  31094. * True if the mesh has some Levels Of Details (LOD).
  31095. * Returns a boolean.
  31096. */
  31097. get: function () {
  31098. return this._LODLevels.length > 0;
  31099. },
  31100. enumerable: true,
  31101. configurable: true
  31102. });
  31103. /**
  31104. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31105. * @returns an array of {BABYLON.MeshLODLevel}
  31106. */
  31107. Mesh.prototype.getLODLevels = function () {
  31108. return this._LODLevels;
  31109. };
  31110. Mesh.prototype._sortLODLevels = function () {
  31111. this._LODLevels.sort(function (a, b) {
  31112. if (a.distance < b.distance) {
  31113. return 1;
  31114. }
  31115. if (a.distance > b.distance) {
  31116. return -1;
  31117. }
  31118. return 0;
  31119. });
  31120. };
  31121. /**
  31122. * Add a mesh as LOD level triggered at the given distance.
  31123. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31124. * @param distance The distance from the center of the object to show this level
  31125. * @param mesh The mesh to be added as LOD level (can be null)
  31126. * @return This mesh (for chaining)
  31127. */
  31128. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31129. if (mesh && mesh._masterMesh) {
  31130. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31131. return this;
  31132. }
  31133. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31134. this._LODLevels.push(level);
  31135. if (mesh) {
  31136. mesh._masterMesh = this;
  31137. }
  31138. this._sortLODLevels();
  31139. return this;
  31140. };
  31141. /**
  31142. * Returns the LOD level mesh at the passed distance or null if not found.
  31143. * It is related to the method `addLODLevel(distance, mesh)`.
  31144. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31145. * Returns an object Mesh or `null`.
  31146. */
  31147. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31148. for (var index = 0; index < this._LODLevels.length; index++) {
  31149. var level = this._LODLevels[index];
  31150. if (level.distance === distance) {
  31151. return level.mesh;
  31152. }
  31153. }
  31154. return null;
  31155. };
  31156. /**
  31157. * Remove a mesh from the LOD array
  31158. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31159. * @param {Mesh} mesh The mesh to be removed.
  31160. * @return {Mesh} This mesh (for chaining)
  31161. */
  31162. Mesh.prototype.removeLODLevel = function (mesh) {
  31163. for (var index = 0; index < this._LODLevels.length; index++) {
  31164. if (this._LODLevels[index].mesh === mesh) {
  31165. this._LODLevels.splice(index, 1);
  31166. if (mesh) {
  31167. mesh._masterMesh = null;
  31168. }
  31169. }
  31170. }
  31171. this._sortLODLevels();
  31172. return this;
  31173. };
  31174. /**
  31175. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31176. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31177. */
  31178. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31179. if (!this._LODLevels || this._LODLevels.length === 0) {
  31180. return this;
  31181. }
  31182. var bSphere;
  31183. if (boundingSphere) {
  31184. bSphere = boundingSphere;
  31185. }
  31186. else {
  31187. var boundingInfo = this.getBoundingInfo();
  31188. bSphere = boundingInfo.boundingSphere;
  31189. }
  31190. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31191. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31192. if (this.onLODLevelSelection) {
  31193. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31194. }
  31195. return this;
  31196. }
  31197. for (var index = 0; index < this._LODLevels.length; index++) {
  31198. var level = this._LODLevels[index];
  31199. if (level.distance < distanceToCamera) {
  31200. if (level.mesh) {
  31201. level.mesh._preActivate();
  31202. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31203. }
  31204. if (this.onLODLevelSelection) {
  31205. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31206. }
  31207. return level.mesh;
  31208. }
  31209. }
  31210. if (this.onLODLevelSelection) {
  31211. this.onLODLevelSelection(distanceToCamera, this, this);
  31212. }
  31213. return this;
  31214. };
  31215. Object.defineProperty(Mesh.prototype, "geometry", {
  31216. /**
  31217. * Returns the mesh internal Geometry object.
  31218. */
  31219. get: function () {
  31220. return this._geometry;
  31221. },
  31222. enumerable: true,
  31223. configurable: true
  31224. });
  31225. /**
  31226. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31227. */
  31228. Mesh.prototype.getTotalVertices = function () {
  31229. if (this._geometry === null || this._geometry === undefined) {
  31230. return 0;
  31231. }
  31232. return this._geometry.getTotalVertices();
  31233. };
  31234. /**
  31235. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31236. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31237. * You can force the copy with forceCopy === true
  31238. * Returns null if the mesh has no geometry or no vertex buffer.
  31239. * Possible `kind` values :
  31240. * - BABYLON.VertexBuffer.PositionKind
  31241. * - BABYLON.VertexBuffer.UVKind
  31242. * - BABYLON.VertexBuffer.UV2Kind
  31243. * - BABYLON.VertexBuffer.UV3Kind
  31244. * - BABYLON.VertexBuffer.UV4Kind
  31245. * - BABYLON.VertexBuffer.UV5Kind
  31246. * - BABYLON.VertexBuffer.UV6Kind
  31247. * - BABYLON.VertexBuffer.ColorKind
  31248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31252. */
  31253. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31254. if (!this._geometry) {
  31255. return null;
  31256. }
  31257. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31258. };
  31259. /**
  31260. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31261. * Returns `null` if the mesh has no geometry.
  31262. * Possible `kind` values :
  31263. * - BABYLON.VertexBuffer.PositionKind
  31264. * - BABYLON.VertexBuffer.UVKind
  31265. * - BABYLON.VertexBuffer.UV2Kind
  31266. * - BABYLON.VertexBuffer.UV3Kind
  31267. * - BABYLON.VertexBuffer.UV4Kind
  31268. * - BABYLON.VertexBuffer.UV5Kind
  31269. * - BABYLON.VertexBuffer.UV6Kind
  31270. * - BABYLON.VertexBuffer.ColorKind
  31271. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31272. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31273. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31274. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31275. */
  31276. Mesh.prototype.getVertexBuffer = function (kind) {
  31277. if (!this._geometry) {
  31278. return null;
  31279. }
  31280. return this._geometry.getVertexBuffer(kind);
  31281. };
  31282. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31283. if (!this._geometry) {
  31284. if (this._delayInfo) {
  31285. return this._delayInfo.indexOf(kind) !== -1;
  31286. }
  31287. return false;
  31288. }
  31289. return this._geometry.isVerticesDataPresent(kind);
  31290. };
  31291. /**
  31292. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31293. * Possible `kind` values :
  31294. * - BABYLON.VertexBuffer.PositionKind
  31295. * - BABYLON.VertexBuffer.UVKind
  31296. * - BABYLON.VertexBuffer.UV2Kind
  31297. * - BABYLON.VertexBuffer.UV3Kind
  31298. * - BABYLON.VertexBuffer.UV4Kind
  31299. * - BABYLON.VertexBuffer.UV5Kind
  31300. * - BABYLON.VertexBuffer.UV6Kind
  31301. * - BABYLON.VertexBuffer.ColorKind
  31302. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31303. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31304. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31305. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31306. */
  31307. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31308. if (!this._geometry) {
  31309. if (this._delayInfo) {
  31310. return this._delayInfo.indexOf(kind) !== -1;
  31311. }
  31312. return false;
  31313. }
  31314. return this._geometry.isVertexBufferUpdatable(kind);
  31315. };
  31316. /**
  31317. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31318. * Possible `kind` values :
  31319. * - BABYLON.VertexBuffer.PositionKind
  31320. * - BABYLON.VertexBuffer.UVKind
  31321. * - BABYLON.VertexBuffer.UV2Kind
  31322. * - BABYLON.VertexBuffer.UV3Kind
  31323. * - BABYLON.VertexBuffer.UV4Kind
  31324. * - BABYLON.VertexBuffer.UV5Kind
  31325. * - BABYLON.VertexBuffer.UV6Kind
  31326. * - BABYLON.VertexBuffer.ColorKind
  31327. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31328. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31329. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31330. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31331. */
  31332. Mesh.prototype.getVerticesDataKinds = function () {
  31333. if (!this._geometry) {
  31334. var result = new Array();
  31335. if (this._delayInfo) {
  31336. this._delayInfo.forEach(function (kind, index, array) {
  31337. result.push(kind);
  31338. });
  31339. }
  31340. return result;
  31341. }
  31342. return this._geometry.getVerticesDataKinds();
  31343. };
  31344. /**
  31345. * Returns a positive integer : the total number of indices in this mesh geometry.
  31346. * Returns zero if the mesh has no geometry.
  31347. */
  31348. Mesh.prototype.getTotalIndices = function () {
  31349. if (!this._geometry) {
  31350. return 0;
  31351. }
  31352. return this._geometry.getTotalIndices();
  31353. };
  31354. /**
  31355. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31356. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31357. * Returns an empty array if the mesh has no geometry.
  31358. */
  31359. Mesh.prototype.getIndices = function (copyWhenShared) {
  31360. if (!this._geometry) {
  31361. return [];
  31362. }
  31363. return this._geometry.getIndices(copyWhenShared);
  31364. };
  31365. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31366. get: function () {
  31367. return this._masterMesh !== null && this._masterMesh !== undefined;
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. /**
  31373. * Determine if the current mesh is ready to be rendered
  31374. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31375. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31376. * @returns true if all associated assets are ready (material, textures, shaders)
  31377. */
  31378. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31379. if (completeCheck === void 0) { completeCheck = false; }
  31380. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31381. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31382. return false;
  31383. }
  31384. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31385. return false;
  31386. }
  31387. if (!this.subMeshes || this.subMeshes.length === 0) {
  31388. return true;
  31389. }
  31390. if (!completeCheck) {
  31391. return true;
  31392. }
  31393. var engine = this.getEngine();
  31394. var scene = this.getScene();
  31395. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31396. this.computeWorldMatrix();
  31397. var mat = this.material || scene.defaultMaterial;
  31398. if (mat) {
  31399. if (mat.storeEffectOnSubMeshes) {
  31400. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31401. var subMesh = _a[_i];
  31402. var effectiveMaterial = subMesh.getMaterial();
  31403. if (effectiveMaterial) {
  31404. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31405. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31406. return false;
  31407. }
  31408. }
  31409. else {
  31410. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31411. return false;
  31412. }
  31413. }
  31414. }
  31415. }
  31416. }
  31417. else {
  31418. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31419. return false;
  31420. }
  31421. }
  31422. }
  31423. // Shadows
  31424. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31425. var light = _c[_b];
  31426. var generator = light.getShadowGenerator();
  31427. if (generator) {
  31428. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31429. var subMesh = _e[_d];
  31430. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31431. return false;
  31432. }
  31433. }
  31434. }
  31435. }
  31436. // LOD
  31437. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31438. var lod = _g[_f];
  31439. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31440. return false;
  31441. }
  31442. }
  31443. return true;
  31444. };
  31445. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31446. /**
  31447. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31448. * This property is pertinent only for updatable parametric shapes.
  31449. */
  31450. get: function () {
  31451. return this._areNormalsFrozen;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. /**
  31457. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31458. * It has no effect at all on other shapes.
  31459. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31460. * Returns the Mesh.
  31461. */
  31462. Mesh.prototype.freezeNormals = function () {
  31463. this._areNormalsFrozen = true;
  31464. return this;
  31465. };
  31466. /**
  31467. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31468. * It has no effect at all on other shapes.
  31469. * It reactivates the mesh normals computation if it was previously frozen.
  31470. * Returns the Mesh.
  31471. */
  31472. Mesh.prototype.unfreezeNormals = function () {
  31473. this._areNormalsFrozen = false;
  31474. return this;
  31475. };
  31476. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31477. /**
  31478. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31479. */
  31480. set: function (count) {
  31481. this._overridenInstanceCount = count;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. // Methods
  31487. Mesh.prototype._preActivate = function () {
  31488. var sceneRenderId = this.getScene().getRenderId();
  31489. if (this._preActivateId === sceneRenderId) {
  31490. return this;
  31491. }
  31492. this._preActivateId = sceneRenderId;
  31493. this._visibleInstances = null;
  31494. return this;
  31495. };
  31496. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31497. if (this._visibleInstances) {
  31498. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31499. }
  31500. return this;
  31501. };
  31502. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31503. if (!this._visibleInstances) {
  31504. this._visibleInstances = {};
  31505. this._visibleInstances.defaultRenderId = renderId;
  31506. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31507. }
  31508. if (!this._visibleInstances[renderId]) {
  31509. this._visibleInstances[renderId] = new Array();
  31510. }
  31511. this._visibleInstances[renderId].push(instance);
  31512. return this;
  31513. };
  31514. /**
  31515. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31516. * This means the mesh underlying bounding box and sphere are recomputed.
  31517. * Returns the Mesh.
  31518. */
  31519. Mesh.prototype.refreshBoundingInfo = function () {
  31520. return this._refreshBoundingInfo(false);
  31521. };
  31522. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31523. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31524. return this;
  31525. }
  31526. var data = this._getPositionData(applySkeleton);
  31527. if (data) {
  31528. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31529. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31530. }
  31531. if (this.subMeshes) {
  31532. for (var index = 0; index < this.subMeshes.length; index++) {
  31533. this.subMeshes[index].refreshBoundingInfo();
  31534. }
  31535. }
  31536. this._updateBoundingInfo();
  31537. return this;
  31538. };
  31539. Mesh.prototype._getPositionData = function (applySkeleton) {
  31540. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31541. if (data && applySkeleton && this.skeleton) {
  31542. data = BABYLON.Tools.Slice(data);
  31543. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31544. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31545. if (matricesWeightsData && matricesIndicesData) {
  31546. var needExtras = this.numBoneInfluencers > 4;
  31547. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31548. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31549. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31550. var tempVector = BABYLON.Tmp.Vector3[0];
  31551. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31552. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31553. var matWeightIdx = 0;
  31554. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31555. finalMatrix.reset();
  31556. var inf;
  31557. var weight;
  31558. for (inf = 0; inf < 4; inf++) {
  31559. weight = matricesWeightsData[matWeightIdx + inf];
  31560. if (weight > 0) {
  31561. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31562. finalMatrix.addToSelf(tempMatrix);
  31563. }
  31564. }
  31565. if (needExtras) {
  31566. for (inf = 0; inf < 4; inf++) {
  31567. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31568. if (weight > 0) {
  31569. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31570. finalMatrix.addToSelf(tempMatrix);
  31571. }
  31572. }
  31573. }
  31574. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31575. tempVector.toArray(data, index);
  31576. }
  31577. }
  31578. }
  31579. return data;
  31580. };
  31581. Mesh.prototype._createGlobalSubMesh = function (force) {
  31582. var totalVertices = this.getTotalVertices();
  31583. if (!totalVertices || !this.getIndices()) {
  31584. return null;
  31585. }
  31586. // Check if we need to recreate the submeshes
  31587. if (this.subMeshes && this.subMeshes.length > 0) {
  31588. var ib = this.getIndices();
  31589. if (!ib) {
  31590. return null;
  31591. }
  31592. var totalIndices = ib.length;
  31593. var needToRecreate = false;
  31594. if (force) {
  31595. needToRecreate = true;
  31596. }
  31597. else {
  31598. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31599. var submesh = _a[_i];
  31600. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31601. needToRecreate = true;
  31602. break;
  31603. }
  31604. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31605. needToRecreate = true;
  31606. break;
  31607. }
  31608. }
  31609. }
  31610. if (!needToRecreate) {
  31611. return this.subMeshes[0];
  31612. }
  31613. }
  31614. this.releaseSubMeshes();
  31615. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31616. };
  31617. Mesh.prototype.subdivide = function (count) {
  31618. if (count < 1) {
  31619. return;
  31620. }
  31621. var totalIndices = this.getTotalIndices();
  31622. var subdivisionSize = (totalIndices / count) | 0;
  31623. var offset = 0;
  31624. // Ensure that subdivisionSize is a multiple of 3
  31625. while (subdivisionSize % 3 !== 0) {
  31626. subdivisionSize++;
  31627. }
  31628. this.releaseSubMeshes();
  31629. for (var index = 0; index < count; index++) {
  31630. if (offset >= totalIndices) {
  31631. break;
  31632. }
  31633. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31634. offset += subdivisionSize;
  31635. }
  31636. this.synchronizeInstances();
  31637. };
  31638. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31639. if (updatable === void 0) { updatable = false; }
  31640. if (!this._geometry) {
  31641. var vertexData = new BABYLON.VertexData();
  31642. vertexData.set(data, kind);
  31643. var scene = this.getScene();
  31644. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31645. }
  31646. else {
  31647. this._geometry.setVerticesData(kind, data, updatable, stride);
  31648. }
  31649. return this;
  31650. };
  31651. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31652. if (updatable === void 0) { updatable = true; }
  31653. var vb = this.getVertexBuffer(kind);
  31654. if (!vb || vb.isUpdatable() === updatable) {
  31655. return;
  31656. }
  31657. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31658. };
  31659. /**
  31660. * Sets the mesh VertexBuffer.
  31661. * Returns the Mesh.
  31662. */
  31663. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31664. if (!this._geometry) {
  31665. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31666. }
  31667. this._geometry.setVerticesBuffer(buffer);
  31668. return this;
  31669. };
  31670. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31671. if (!this._geometry) {
  31672. return this;
  31673. }
  31674. if (!makeItUnique) {
  31675. this._geometry.updateVerticesData(kind, data, updateExtends);
  31676. }
  31677. else {
  31678. this.makeGeometryUnique();
  31679. this.updateVerticesData(kind, data, updateExtends, false);
  31680. }
  31681. return this;
  31682. };
  31683. /**
  31684. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31685. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31686. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31687. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31688. * Returns the Mesh.
  31689. */
  31690. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31691. if (computeNormals === void 0) { computeNormals = true; }
  31692. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31693. if (!positions) {
  31694. return this;
  31695. }
  31696. positionFunction(positions);
  31697. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31698. if (computeNormals) {
  31699. var indices = this.getIndices();
  31700. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31701. if (!normals) {
  31702. return this;
  31703. }
  31704. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31705. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31706. }
  31707. return this;
  31708. };
  31709. /**
  31710. * Creates a un-shared specific occurence of the geometry for the mesh.
  31711. * Returns the Mesh.
  31712. */
  31713. Mesh.prototype.makeGeometryUnique = function () {
  31714. if (!this._geometry) {
  31715. return this;
  31716. }
  31717. var oldGeometry = this._geometry;
  31718. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31719. oldGeometry.releaseForMesh(this, true);
  31720. geometry.applyToMesh(this);
  31721. return this;
  31722. };
  31723. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31724. if (totalVertices === void 0) { totalVertices = null; }
  31725. if (updatable === void 0) { updatable = false; }
  31726. if (!this._geometry) {
  31727. var vertexData = new BABYLON.VertexData();
  31728. vertexData.indices = indices;
  31729. var scene = this.getScene();
  31730. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31731. }
  31732. else {
  31733. this._geometry.setIndices(indices, totalVertices, updatable);
  31734. }
  31735. return this;
  31736. };
  31737. /**
  31738. * Update the current index buffer
  31739. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31740. * Returns the Mesh.
  31741. */
  31742. Mesh.prototype.updateIndices = function (indices, offset) {
  31743. if (!this._geometry) {
  31744. return this;
  31745. }
  31746. this._geometry.updateIndices(indices, offset);
  31747. return this;
  31748. };
  31749. /**
  31750. * Invert the geometry to move from a right handed system to a left handed one.
  31751. * Returns the Mesh.
  31752. */
  31753. Mesh.prototype.toLeftHanded = function () {
  31754. if (!this._geometry) {
  31755. return this;
  31756. }
  31757. this._geometry.toLeftHanded();
  31758. return this;
  31759. };
  31760. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31761. if (!this._geometry) {
  31762. return this;
  31763. }
  31764. var engine = this.getScene().getEngine();
  31765. // Wireframe
  31766. var indexToBind;
  31767. if (this._unIndexed) {
  31768. indexToBind = null;
  31769. }
  31770. else {
  31771. switch (fillMode) {
  31772. case BABYLON.Material.PointFillMode:
  31773. indexToBind = null;
  31774. break;
  31775. case BABYLON.Material.WireFrameFillMode:
  31776. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31777. break;
  31778. default:
  31779. case BABYLON.Material.TriangleFillMode:
  31780. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31781. break;
  31782. }
  31783. }
  31784. // VBOs
  31785. this._geometry._bind(effect, indexToBind);
  31786. return this;
  31787. };
  31788. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31789. if (alternate === void 0) { alternate = false; }
  31790. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31791. return this;
  31792. }
  31793. this.onBeforeDrawObservable.notifyObservers(this);
  31794. var scene = this.getScene();
  31795. var engine = scene.getEngine();
  31796. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31797. // or triangles as points
  31798. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31799. }
  31800. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31801. // Triangles as wireframe
  31802. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31803. }
  31804. else {
  31805. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31806. }
  31807. if (scene._isAlternateRenderingEnabled && !alternate) {
  31808. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31809. if (!effect || !scene.activeCamera) {
  31810. return this;
  31811. }
  31812. scene._switchToAlternateCameraConfiguration(true);
  31813. this._effectiveMaterial.bindView(effect);
  31814. this._effectiveMaterial.bindViewProjection(effect);
  31815. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31816. this._draw(subMesh, fillMode, instancesCount, true);
  31817. engine.setViewport(scene.activeCamera.viewport);
  31818. scene._switchToAlternateCameraConfiguration(false);
  31819. this._effectiveMaterial.bindView(effect);
  31820. this._effectiveMaterial.bindViewProjection(effect);
  31821. }
  31822. return this;
  31823. };
  31824. /**
  31825. * Registers for this mesh a javascript function called just before the rendering process.
  31826. * This function is passed the current mesh.
  31827. * Return the Mesh.
  31828. */
  31829. Mesh.prototype.registerBeforeRender = function (func) {
  31830. this.onBeforeRenderObservable.add(func);
  31831. return this;
  31832. };
  31833. /**
  31834. * Disposes a previously registered javascript function called before the rendering.
  31835. * This function is passed the current mesh.
  31836. * Returns the Mesh.
  31837. */
  31838. Mesh.prototype.unregisterBeforeRender = function (func) {
  31839. this.onBeforeRenderObservable.removeCallback(func);
  31840. return this;
  31841. };
  31842. /**
  31843. * Registers for this mesh a javascript function called just after the rendering is complete.
  31844. * This function is passed the current mesh.
  31845. * Returns the Mesh.
  31846. */
  31847. Mesh.prototype.registerAfterRender = function (func) {
  31848. this.onAfterRenderObservable.add(func);
  31849. return this;
  31850. };
  31851. /**
  31852. * Disposes a previously registered javascript function called after the rendering.
  31853. * This function is passed the current mesh.
  31854. * Return the Mesh.
  31855. */
  31856. Mesh.prototype.unregisterAfterRender = function (func) {
  31857. this.onAfterRenderObservable.removeCallback(func);
  31858. return this;
  31859. };
  31860. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31861. var scene = this.getScene();
  31862. this._batchCache.mustReturn = false;
  31863. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31864. this._batchCache.visibleInstances[subMeshId] = null;
  31865. if (this._visibleInstances) {
  31866. var currentRenderId = scene.getRenderId();
  31867. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31868. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31869. var selfRenderId = this._renderId;
  31870. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31871. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31872. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31873. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31874. }
  31875. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31876. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31877. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31878. this._batchCache.mustReturn = true;
  31879. return this._batchCache;
  31880. }
  31881. if (currentRenderId !== selfRenderId) {
  31882. this._batchCache.renderSelf[subMeshId] = false;
  31883. }
  31884. }
  31885. this._renderIdForInstances[subMeshId] = currentRenderId;
  31886. }
  31887. return this._batchCache;
  31888. };
  31889. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31890. var visibleInstances = batch.visibleInstances[subMesh._id];
  31891. if (!visibleInstances) {
  31892. return this;
  31893. }
  31894. var matricesCount = visibleInstances.length + 1;
  31895. var bufferSize = matricesCount * 16 * 4;
  31896. var currentInstancesBufferSize = this._instancesBufferSize;
  31897. var instancesBuffer = this._instancesBuffer;
  31898. while (this._instancesBufferSize < bufferSize) {
  31899. this._instancesBufferSize *= 2;
  31900. }
  31901. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31902. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31903. }
  31904. var offset = 0;
  31905. var instancesCount = 0;
  31906. var world = this.getWorldMatrix();
  31907. if (batch.renderSelf[subMesh._id]) {
  31908. world.copyToArray(this._instancesData, offset);
  31909. offset += 16;
  31910. instancesCount++;
  31911. }
  31912. if (visibleInstances) {
  31913. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31914. var instance = visibleInstances[instanceIndex];
  31915. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31916. offset += 16;
  31917. instancesCount++;
  31918. }
  31919. }
  31920. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31921. if (instancesBuffer) {
  31922. instancesBuffer.dispose();
  31923. }
  31924. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31925. this._instancesBuffer = instancesBuffer;
  31926. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31927. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31928. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31929. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31930. }
  31931. else {
  31932. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31933. }
  31934. this._bind(subMesh, effect, fillMode);
  31935. this._draw(subMesh, fillMode, instancesCount);
  31936. engine.unbindInstanceAttributes();
  31937. return this;
  31938. };
  31939. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31940. var scene = this.getScene();
  31941. var engine = scene.getEngine();
  31942. if (hardwareInstancedRendering) {
  31943. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31944. }
  31945. else {
  31946. if (batch.renderSelf[subMesh._id]) {
  31947. // Draw
  31948. if (onBeforeDraw) {
  31949. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31950. }
  31951. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31952. }
  31953. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31954. if (visibleInstancesForSubMesh) {
  31955. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31956. var instance = visibleInstancesForSubMesh[instanceIndex];
  31957. // World
  31958. var world = instance.getWorldMatrix();
  31959. if (onBeforeDraw) {
  31960. onBeforeDraw(true, world, effectiveMaterial);
  31961. }
  31962. // Draw
  31963. this._draw(subMesh, fillMode);
  31964. }
  31965. }
  31966. }
  31967. return this;
  31968. };
  31969. /**
  31970. * 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
  31971. * @param subMesh defines the subMesh to render
  31972. * @param enableAlphaMode defines if alpha mode can be changed
  31973. * @returns the current mesh
  31974. */
  31975. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31976. this._checkOcclusionQuery();
  31977. if (this._isOccluded) {
  31978. return this;
  31979. }
  31980. var scene = this.getScene();
  31981. // Managing instances
  31982. var batch = this._getInstancesRenderList(subMesh._id);
  31983. if (batch.mustReturn) {
  31984. return this;
  31985. }
  31986. // Checking geometry state
  31987. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31988. return this;
  31989. }
  31990. this.onBeforeRenderObservable.notifyObservers(this);
  31991. var engine = scene.getEngine();
  31992. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31993. // Material
  31994. var material = subMesh.getMaterial();
  31995. if (!material) {
  31996. return this;
  31997. }
  31998. this._effectiveMaterial = material;
  31999. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32000. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32001. return this;
  32002. }
  32003. }
  32004. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32005. return this;
  32006. }
  32007. // Alpha mode
  32008. if (enableAlphaMode) {
  32009. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32010. }
  32011. // Outline - step 1
  32012. var savedDepthWrite = engine.getDepthWrite();
  32013. if (this.renderOutline) {
  32014. engine.setDepthWrite(false);
  32015. scene.getOutlineRenderer().render(subMesh, batch);
  32016. engine.setDepthWrite(savedDepthWrite);
  32017. }
  32018. var effect;
  32019. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32020. effect = subMesh.effect;
  32021. }
  32022. else {
  32023. effect = this._effectiveMaterial.getEffect();
  32024. }
  32025. if (!effect) {
  32026. return this;
  32027. }
  32028. var sideOrientation = this.overrideMaterialSideOrientation;
  32029. if (sideOrientation == null) {
  32030. sideOrientation = this._effectiveMaterial.sideOrientation;
  32031. if (this._getWorldMatrixDeterminant() < 0) {
  32032. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32033. }
  32034. }
  32035. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32036. if (this._effectiveMaterial.forceDepthWrite) {
  32037. engine.setDepthWrite(true);
  32038. }
  32039. // Bind
  32040. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32041. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32042. this._bind(subMesh, effect, fillMode);
  32043. }
  32044. var world = this.getWorldMatrix();
  32045. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32046. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32047. }
  32048. else {
  32049. this._effectiveMaterial.bind(world, this);
  32050. }
  32051. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32052. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32053. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32054. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32055. }
  32056. // Draw
  32057. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32058. // Unbind
  32059. this._effectiveMaterial.unbind();
  32060. // Outline - step 2
  32061. if (this.renderOutline && savedDepthWrite) {
  32062. engine.setDepthWrite(true);
  32063. engine.setColorWrite(false);
  32064. scene.getOutlineRenderer().render(subMesh, batch);
  32065. engine.setColorWrite(true);
  32066. }
  32067. // Overlay
  32068. if (this.renderOverlay) {
  32069. var currentMode = engine.getAlphaMode();
  32070. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32071. scene.getOutlineRenderer().render(subMesh, batch, true);
  32072. engine.setAlphaMode(currentMode);
  32073. }
  32074. this.onAfterRenderObservable.notifyObservers(this);
  32075. return this;
  32076. };
  32077. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32078. if (isInstance && effectiveMaterial) {
  32079. effectiveMaterial.bindOnlyWorldMatrix(world);
  32080. }
  32081. };
  32082. /**
  32083. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32084. */
  32085. Mesh.prototype.getEmittedParticleSystems = function () {
  32086. var results = new Array();
  32087. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32088. var particleSystem = this.getScene().particleSystems[index];
  32089. if (particleSystem.emitter === this) {
  32090. results.push(particleSystem);
  32091. }
  32092. }
  32093. return results;
  32094. };
  32095. /**
  32096. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32097. */
  32098. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32099. var results = new Array();
  32100. var descendants = this.getDescendants();
  32101. descendants.push(this);
  32102. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32103. var particleSystem = this.getScene().particleSystems[index];
  32104. var emitter = particleSystem.emitter;
  32105. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32106. results.push(particleSystem);
  32107. }
  32108. }
  32109. return results;
  32110. };
  32111. /**
  32112. * Normalize matrix weights so that all vertices have a total weight set to 1
  32113. */
  32114. Mesh.prototype.cleanMatrixWeights = function () {
  32115. var epsilon = 1e-3;
  32116. var noInfluenceBoneIndex = 0.0;
  32117. if (this.skeleton) {
  32118. noInfluenceBoneIndex = this.skeleton.bones.length;
  32119. }
  32120. else {
  32121. return;
  32122. }
  32123. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32124. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32125. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32126. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32127. var influencers = this.numBoneInfluencers;
  32128. var size = matricesWeights.length;
  32129. for (var i = 0; i < size; i += 4) {
  32130. var weight = 0.0;
  32131. var firstZeroWeight = -1;
  32132. for (var j = 0; j < 4; j++) {
  32133. var w = matricesWeights[i + j];
  32134. weight += w;
  32135. if (w < epsilon && firstZeroWeight < 0) {
  32136. firstZeroWeight = j;
  32137. }
  32138. }
  32139. if (matricesWeightsExtra) {
  32140. for (var j = 0; j < 4; j++) {
  32141. var w = matricesWeightsExtra[i + j];
  32142. weight += w;
  32143. if (w < epsilon && firstZeroWeight < 0) {
  32144. firstZeroWeight = j + 4;
  32145. }
  32146. }
  32147. }
  32148. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32149. firstZeroWeight = influencers - 1;
  32150. }
  32151. if (weight > epsilon) {
  32152. var mweight = 1.0 / weight;
  32153. for (var j = 0; j < 4; j++) {
  32154. matricesWeights[i + j] *= mweight;
  32155. }
  32156. if (matricesWeightsExtra) {
  32157. for (var j = 0; j < 4; j++) {
  32158. matricesWeightsExtra[i + j] *= mweight;
  32159. }
  32160. }
  32161. }
  32162. else {
  32163. if (firstZeroWeight >= 4) {
  32164. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32165. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32166. }
  32167. else {
  32168. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32169. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32170. }
  32171. }
  32172. }
  32173. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32174. if (matricesIndicesExtra) {
  32175. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32176. }
  32177. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32178. if (matricesWeightsExtra) {
  32179. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32180. }
  32181. };
  32182. Mesh.prototype._checkDelayState = function () {
  32183. var scene = this.getScene();
  32184. if (this._geometry) {
  32185. this._geometry.load(scene);
  32186. }
  32187. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32188. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32189. this._queueLoad(scene);
  32190. }
  32191. return this;
  32192. };
  32193. Mesh.prototype._queueLoad = function (scene) {
  32194. var _this = this;
  32195. scene._addPendingData(this);
  32196. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32197. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32198. if (data instanceof ArrayBuffer) {
  32199. _this._delayLoadingFunction(data, _this);
  32200. }
  32201. else {
  32202. _this._delayLoadingFunction(JSON.parse(data), _this);
  32203. }
  32204. _this.instances.forEach(function (instance) {
  32205. instance._syncSubMeshes();
  32206. });
  32207. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32208. scene._removePendingData(_this);
  32209. }, function () { }, scene.database, getBinaryData);
  32210. return this;
  32211. };
  32212. /**
  32213. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32214. */
  32215. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32216. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32217. return false;
  32218. }
  32219. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32220. return false;
  32221. }
  32222. this._checkDelayState();
  32223. return true;
  32224. };
  32225. /**
  32226. * Sets the mesh material by the material or multiMaterial `id` property.
  32227. * The material `id` is a string identifying the material or the multiMaterial.
  32228. * This method returns the Mesh.
  32229. */
  32230. Mesh.prototype.setMaterialByID = function (id) {
  32231. var materials = this.getScene().materials;
  32232. var index;
  32233. for (index = materials.length - 1; index > -1; index--) {
  32234. if (materials[index].id === id) {
  32235. this.material = materials[index];
  32236. return this;
  32237. }
  32238. }
  32239. // Multi
  32240. var multiMaterials = this.getScene().multiMaterials;
  32241. for (index = multiMaterials.length - 1; index > -1; index--) {
  32242. if (multiMaterials[index].id === id) {
  32243. this.material = multiMaterials[index];
  32244. return this;
  32245. }
  32246. }
  32247. return this;
  32248. };
  32249. /**
  32250. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32251. */
  32252. Mesh.prototype.getAnimatables = function () {
  32253. var results = new Array();
  32254. if (this.material) {
  32255. results.push(this.material);
  32256. }
  32257. if (this.skeleton) {
  32258. results.push(this.skeleton);
  32259. }
  32260. return results;
  32261. };
  32262. /**
  32263. * Modifies the mesh geometry according to the passed transformation matrix.
  32264. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32265. * The mesh normals are modified accordingly the same transformation.
  32266. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32267. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32268. * Returns the Mesh.
  32269. */
  32270. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32271. // Position
  32272. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32273. return this;
  32274. }
  32275. var submeshes = this.subMeshes.splice(0);
  32276. this._resetPointsArrayCache();
  32277. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32278. var temp = new Array();
  32279. var index;
  32280. for (index = 0; index < data.length; index += 3) {
  32281. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32282. }
  32283. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32284. // Normals
  32285. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32286. return this;
  32287. }
  32288. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32289. temp = [];
  32290. for (index = 0; index < data.length; index += 3) {
  32291. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32292. }
  32293. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32294. // flip faces?
  32295. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32296. this.flipFaces();
  32297. }
  32298. // Restore submeshes
  32299. this.releaseSubMeshes();
  32300. this.subMeshes = submeshes;
  32301. return this;
  32302. };
  32303. /**
  32304. * Modifies the mesh geometry according to its own current World Matrix.
  32305. * The mesh World Matrix is then reset.
  32306. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32307. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32308. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32309. * Returns the Mesh.
  32310. */
  32311. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32312. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32313. this.scaling.copyFromFloats(1, 1, 1);
  32314. this.position.copyFromFloats(0, 0, 0);
  32315. this.rotation.copyFromFloats(0, 0, 0);
  32316. //only if quaternion is already set
  32317. if (this.rotationQuaternion) {
  32318. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32319. }
  32320. this._worldMatrix = BABYLON.Matrix.Identity();
  32321. return this;
  32322. };
  32323. Object.defineProperty(Mesh.prototype, "_positions", {
  32324. // Cache
  32325. get: function () {
  32326. if (this._geometry) {
  32327. return this._geometry._positions;
  32328. }
  32329. return null;
  32330. },
  32331. enumerable: true,
  32332. configurable: true
  32333. });
  32334. Mesh.prototype._resetPointsArrayCache = function () {
  32335. if (this._geometry) {
  32336. this._geometry._resetPointsArrayCache();
  32337. }
  32338. return this;
  32339. };
  32340. Mesh.prototype._generatePointsArray = function () {
  32341. if (this._geometry) {
  32342. return this._geometry._generatePointsArray();
  32343. }
  32344. return false;
  32345. };
  32346. /**
  32347. * Returns a new Mesh object generated from the current mesh properties.
  32348. * This method must not get confused with createInstance().
  32349. * The parameter `name` is a string, the name given to the new mesh.
  32350. * The optional parameter `newParent` can be any Node object (default `null`).
  32351. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32352. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  32353. */
  32354. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32355. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32356. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32357. };
  32358. /**
  32359. * Releases resources associated with this mesh.
  32360. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32361. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32362. */
  32363. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32364. var _this = this;
  32365. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32366. this.morphTargetManager = null;
  32367. if (this._geometry) {
  32368. this._geometry.releaseForMesh(this, true);
  32369. }
  32370. // Sources
  32371. var meshes = this.getScene().meshes;
  32372. meshes.forEach(function (abstractMesh) {
  32373. var mesh = abstractMesh;
  32374. if (mesh._source && mesh._source === _this) {
  32375. mesh._source = null;
  32376. }
  32377. });
  32378. this._source = null;
  32379. // Instances
  32380. if (this._instancesBuffer) {
  32381. this._instancesBuffer.dispose();
  32382. this._instancesBuffer = null;
  32383. }
  32384. while (this.instances.length) {
  32385. this.instances[0].dispose();
  32386. }
  32387. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32388. };
  32389. /**
  32390. * Modifies the mesh geometry according to a displacement map.
  32391. * 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.
  32392. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32393. * This method returns nothing.
  32394. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32395. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32396. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  32397. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32398. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32399. *
  32400. * Returns the Mesh.
  32401. */
  32402. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32403. var _this = this;
  32404. var scene = this.getScene();
  32405. var onload = function (img) {
  32406. // Getting height map data
  32407. var canvas = document.createElement("canvas");
  32408. var context = canvas.getContext("2d");
  32409. var heightMapWidth = img.width;
  32410. var heightMapHeight = img.height;
  32411. canvas.width = heightMapWidth;
  32412. canvas.height = heightMapHeight;
  32413. context.drawImage(img, 0, 0);
  32414. // Create VertexData from map data
  32415. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32416. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32417. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32418. //execute success callback, if set
  32419. if (onSuccess) {
  32420. onSuccess(_this);
  32421. }
  32422. };
  32423. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32424. return this;
  32425. };
  32426. /**
  32427. * Modifies the mesh geometry according to a displacementMap buffer.
  32428. * 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.
  32429. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32430. * This method returns nothing.
  32431. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32432. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32433. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32434. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32435. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32436. *
  32437. * Returns the Mesh.
  32438. */
  32439. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32440. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32441. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32442. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32443. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32444. return this;
  32445. }
  32446. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32447. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32448. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32449. var position = BABYLON.Vector3.Zero();
  32450. var normal = BABYLON.Vector3.Zero();
  32451. var uv = BABYLON.Vector2.Zero();
  32452. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32453. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32454. for (var index = 0; index < positions.length; index += 3) {
  32455. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32456. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32457. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32458. // Compute height
  32459. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32460. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32461. var pos = (u + v * heightMapWidth) * 4;
  32462. var r = buffer[pos] / 255.0;
  32463. var g = buffer[pos + 1] / 255.0;
  32464. var b = buffer[pos + 2] / 255.0;
  32465. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32466. normal.normalize();
  32467. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32468. position = position.add(normal);
  32469. position.toArray(positions, index);
  32470. }
  32471. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32472. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32473. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32474. return this;
  32475. };
  32476. /**
  32477. * Modify the mesh to get a flat shading rendering.
  32478. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32479. * This method returns the Mesh.
  32480. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32481. */
  32482. Mesh.prototype.convertToFlatShadedMesh = function () {
  32483. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32484. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32485. var kinds = this.getVerticesDataKinds();
  32486. var vbs = {};
  32487. var data = {};
  32488. var newdata = {};
  32489. var updatableNormals = false;
  32490. var kindIndex;
  32491. var kind;
  32492. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32493. kind = kinds[kindIndex];
  32494. var vertexBuffer = this.getVertexBuffer(kind);
  32495. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32496. updatableNormals = vertexBuffer.isUpdatable();
  32497. kinds.splice(kindIndex, 1);
  32498. kindIndex--;
  32499. continue;
  32500. }
  32501. vbs[kind] = vertexBuffer;
  32502. data[kind] = vbs[kind].getData();
  32503. newdata[kind] = [];
  32504. }
  32505. // Save previous submeshes
  32506. var previousSubmeshes = this.subMeshes.slice(0);
  32507. var indices = this.getIndices();
  32508. var totalIndices = this.getTotalIndices();
  32509. // Generating unique vertices per face
  32510. var index;
  32511. for (index = 0; index < totalIndices; index++) {
  32512. var vertexIndex = indices[index];
  32513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32514. kind = kinds[kindIndex];
  32515. var stride = vbs[kind].getStrideSize();
  32516. for (var offset = 0; offset < stride; offset++) {
  32517. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32518. }
  32519. }
  32520. }
  32521. // Updating faces & normal
  32522. var normals = [];
  32523. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32524. for (index = 0; index < totalIndices; index += 3) {
  32525. indices[index] = index;
  32526. indices[index + 1] = index + 1;
  32527. indices[index + 2] = index + 2;
  32528. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32529. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32530. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32531. var p1p2 = p1.subtract(p2);
  32532. var p3p2 = p3.subtract(p2);
  32533. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32534. // Store same normals for every vertex
  32535. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32536. normals.push(normal.x);
  32537. normals.push(normal.y);
  32538. normals.push(normal.z);
  32539. }
  32540. }
  32541. this.setIndices(indices);
  32542. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32543. // Updating vertex buffers
  32544. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32545. kind = kinds[kindIndex];
  32546. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32547. }
  32548. // Updating submeshes
  32549. this.releaseSubMeshes();
  32550. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32551. var previousOne = previousSubmeshes[submeshIndex];
  32552. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32553. }
  32554. this.synchronizeInstances();
  32555. return this;
  32556. };
  32557. /**
  32558. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32559. * In other words, more vertices, no more indices and a single bigger VBO.
  32560. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32561. * Returns the Mesh.
  32562. */
  32563. Mesh.prototype.convertToUnIndexedMesh = function () {
  32564. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32565. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32566. var kinds = this.getVerticesDataKinds();
  32567. var vbs = {};
  32568. var data = {};
  32569. var newdata = {};
  32570. var kindIndex;
  32571. var kind;
  32572. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32573. kind = kinds[kindIndex];
  32574. var vertexBuffer = this.getVertexBuffer(kind);
  32575. vbs[kind] = vertexBuffer;
  32576. data[kind] = vbs[kind].getData();
  32577. newdata[kind] = [];
  32578. }
  32579. // Save previous submeshes
  32580. var previousSubmeshes = this.subMeshes.slice(0);
  32581. var indices = this.getIndices();
  32582. var totalIndices = this.getTotalIndices();
  32583. // Generating unique vertices per face
  32584. var index;
  32585. for (index = 0; index < totalIndices; index++) {
  32586. var vertexIndex = indices[index];
  32587. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32588. kind = kinds[kindIndex];
  32589. var stride = vbs[kind].getStrideSize();
  32590. for (var offset = 0; offset < stride; offset++) {
  32591. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32592. }
  32593. }
  32594. }
  32595. // Updating indices
  32596. for (index = 0; index < totalIndices; index += 3) {
  32597. indices[index] = index;
  32598. indices[index + 1] = index + 1;
  32599. indices[index + 2] = index + 2;
  32600. }
  32601. this.setIndices(indices);
  32602. // Updating vertex buffers
  32603. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32604. kind = kinds[kindIndex];
  32605. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32606. }
  32607. // Updating submeshes
  32608. this.releaseSubMeshes();
  32609. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32610. var previousOne = previousSubmeshes[submeshIndex];
  32611. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32612. }
  32613. this._unIndexed = true;
  32614. this.synchronizeInstances();
  32615. return this;
  32616. };
  32617. /**
  32618. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32619. * This method returns the Mesh.
  32620. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32621. */
  32622. Mesh.prototype.flipFaces = function (flipNormals) {
  32623. if (flipNormals === void 0) { flipNormals = false; }
  32624. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32625. var i;
  32626. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32627. for (i = 0; i < vertex_data.normals.length; i++) {
  32628. vertex_data.normals[i] *= -1;
  32629. }
  32630. }
  32631. if (vertex_data.indices) {
  32632. var temp;
  32633. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32634. // reassign indices
  32635. temp = vertex_data.indices[i + 1];
  32636. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32637. vertex_data.indices[i + 2] = temp;
  32638. }
  32639. }
  32640. vertex_data.applyToMesh(this);
  32641. return this;
  32642. };
  32643. // Instances
  32644. /**
  32645. * Creates a new InstancedMesh object from the mesh model.
  32646. * An instance shares the same properties and the same material than its model.
  32647. * Only these properties of each instance can then be set individually :
  32648. * - position
  32649. * - rotation
  32650. * - rotationQuaternion
  32651. * - setPivotMatrix
  32652. * - scaling
  32653. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32654. * Warning : this method is not supported for Line mesh and LineSystem
  32655. */
  32656. Mesh.prototype.createInstance = function (name) {
  32657. return new BABYLON.InstancedMesh(name, this);
  32658. };
  32659. /**
  32660. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32661. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32662. * This method returns the Mesh.
  32663. */
  32664. Mesh.prototype.synchronizeInstances = function () {
  32665. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32666. var instance = this.instances[instanceIndex];
  32667. instance._syncSubMeshes();
  32668. }
  32669. return this;
  32670. };
  32671. /**
  32672. * Simplify the mesh according to the given array of settings.
  32673. * Function will return immediately and will simplify async. It returns the Mesh.
  32674. * @param settings a collection of simplification settings.
  32675. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32676. * @param type the type of simplification to run.
  32677. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32678. */
  32679. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32680. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32681. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32682. this.getScene().simplificationQueue.addTask({
  32683. settings: settings,
  32684. parallelProcessing: parallelProcessing,
  32685. mesh: this,
  32686. simplificationType: simplificationType,
  32687. successCallback: successCallback
  32688. });
  32689. return this;
  32690. };
  32691. /**
  32692. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32693. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32694. * This should be used together with the simplification to avoid disappearing triangles.
  32695. * Returns the Mesh.
  32696. * @param successCallback an optional success callback to be called after the optimization finished.
  32697. */
  32698. Mesh.prototype.optimizeIndices = function (successCallback) {
  32699. var _this = this;
  32700. var indices = this.getIndices();
  32701. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32702. if (!positions || !indices) {
  32703. return this;
  32704. }
  32705. var vectorPositions = new Array();
  32706. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32707. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32708. }
  32709. var dupes = new Array();
  32710. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32711. var realPos = vectorPositions.length - 1 - iteration;
  32712. var testedPosition = vectorPositions[realPos];
  32713. for (var j = 0; j < realPos; ++j) {
  32714. var againstPosition = vectorPositions[j];
  32715. if (testedPosition.equals(againstPosition)) {
  32716. dupes[realPos] = j;
  32717. break;
  32718. }
  32719. }
  32720. }, function () {
  32721. for (var i = 0; i < indices.length; ++i) {
  32722. indices[i] = dupes[indices[i]] || indices[i];
  32723. }
  32724. //indices are now reordered
  32725. var originalSubMeshes = _this.subMeshes.slice(0);
  32726. _this.setIndices(indices);
  32727. _this.subMeshes = originalSubMeshes;
  32728. if (successCallback) {
  32729. successCallback(_this);
  32730. }
  32731. });
  32732. return this;
  32733. };
  32734. Mesh.prototype.serialize = function (serializationObject) {
  32735. serializationObject.name = this.name;
  32736. serializationObject.id = this.id;
  32737. serializationObject.type = this.getClassName();
  32738. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32739. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32740. }
  32741. serializationObject.position = this.position.asArray();
  32742. if (this.rotationQuaternion) {
  32743. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32744. }
  32745. else if (this.rotation) {
  32746. serializationObject.rotation = this.rotation.asArray();
  32747. }
  32748. serializationObject.scaling = this.scaling.asArray();
  32749. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32750. serializationObject.isEnabled = this.isEnabled(false);
  32751. serializationObject.isVisible = this.isVisible;
  32752. serializationObject.infiniteDistance = this.infiniteDistance;
  32753. serializationObject.pickable = this.isPickable;
  32754. serializationObject.receiveShadows = this.receiveShadows;
  32755. serializationObject.billboardMode = this.billboardMode;
  32756. serializationObject.visibility = this.visibility;
  32757. serializationObject.checkCollisions = this.checkCollisions;
  32758. serializationObject.isBlocker = this.isBlocker;
  32759. // Parent
  32760. if (this.parent) {
  32761. serializationObject.parentId = this.parent.id;
  32762. }
  32763. // Geometry
  32764. serializationObject.isUnIndexed = this.isUnIndexed;
  32765. var geometry = this._geometry;
  32766. if (geometry) {
  32767. var geometryId = geometry.id;
  32768. serializationObject.geometryId = geometryId;
  32769. // SubMeshes
  32770. serializationObject.subMeshes = [];
  32771. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32772. var subMesh = this.subMeshes[subIndex];
  32773. serializationObject.subMeshes.push({
  32774. materialIndex: subMesh.materialIndex,
  32775. verticesStart: subMesh.verticesStart,
  32776. verticesCount: subMesh.verticesCount,
  32777. indexStart: subMesh.indexStart,
  32778. indexCount: subMesh.indexCount
  32779. });
  32780. }
  32781. }
  32782. // Material
  32783. if (this.material) {
  32784. serializationObject.materialId = this.material.id;
  32785. }
  32786. else {
  32787. this.material = null;
  32788. }
  32789. // Morph targets
  32790. if (this.morphTargetManager) {
  32791. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32792. }
  32793. // Skeleton
  32794. if (this.skeleton) {
  32795. serializationObject.skeletonId = this.skeleton.id;
  32796. }
  32797. // Physics
  32798. //TODO implement correct serialization for physics impostors.
  32799. var impostor = this.getPhysicsImpostor();
  32800. if (impostor) {
  32801. serializationObject.physicsMass = impostor.getParam("mass");
  32802. serializationObject.physicsFriction = impostor.getParam("friction");
  32803. serializationObject.physicsRestitution = impostor.getParam("mass");
  32804. serializationObject.physicsImpostor = impostor.type;
  32805. }
  32806. // Metadata
  32807. if (this.metadata) {
  32808. serializationObject.metadata = this.metadata;
  32809. }
  32810. // Instances
  32811. serializationObject.instances = [];
  32812. for (var index = 0; index < this.instances.length; index++) {
  32813. var instance = this.instances[index];
  32814. var serializationInstance = {
  32815. name: instance.name,
  32816. id: instance.id,
  32817. position: instance.position.asArray(),
  32818. scaling: instance.scaling.asArray()
  32819. };
  32820. if (instance.rotationQuaternion) {
  32821. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32822. }
  32823. else if (instance.rotation) {
  32824. serializationInstance.rotation = instance.rotation.asArray();
  32825. }
  32826. serializationObject.instances.push(serializationInstance);
  32827. // Animations
  32828. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32829. serializationInstance.ranges = instance.serializeAnimationRanges();
  32830. }
  32831. //
  32832. // Animations
  32833. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32834. serializationObject.ranges = this.serializeAnimationRanges();
  32835. // Layer mask
  32836. serializationObject.layerMask = this.layerMask;
  32837. // Alpha
  32838. serializationObject.alphaIndex = this.alphaIndex;
  32839. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32840. // Overlay
  32841. serializationObject.overlayAlpha = this.overlayAlpha;
  32842. serializationObject.overlayColor = this.overlayColor.asArray();
  32843. serializationObject.renderOverlay = this.renderOverlay;
  32844. // Fog
  32845. serializationObject.applyFog = this.applyFog;
  32846. // Action Manager
  32847. if (this.actionManager) {
  32848. serializationObject.actions = this.actionManager.serialize(this.name);
  32849. }
  32850. };
  32851. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32852. if (!this.geometry) {
  32853. return;
  32854. }
  32855. this._markSubMeshesAsAttributesDirty();
  32856. var morphTargetManager = this._morphTargetManager;
  32857. if (morphTargetManager && morphTargetManager.vertexCount) {
  32858. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32859. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32860. this.morphTargetManager = null;
  32861. return;
  32862. }
  32863. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32864. var morphTarget = morphTargetManager.getActiveTarget(index);
  32865. var positions = morphTarget.getPositions();
  32866. if (!positions) {
  32867. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32868. return;
  32869. }
  32870. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32871. var normals = morphTarget.getNormals();
  32872. if (normals) {
  32873. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32874. }
  32875. var tangents = morphTarget.getTangents();
  32876. if (tangents) {
  32877. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32878. }
  32879. }
  32880. }
  32881. else {
  32882. var index = 0;
  32883. // Positions
  32884. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32885. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32886. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32887. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32888. }
  32889. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32890. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32891. }
  32892. index++;
  32893. }
  32894. }
  32895. };
  32896. // Statics
  32897. /**
  32898. * Returns a new Mesh object parsed from the source provided.
  32899. * The parameter `parsedMesh` is the source.
  32900. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32901. */
  32902. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32903. var mesh;
  32904. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32905. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32906. }
  32907. else {
  32908. mesh = new Mesh(parsedMesh.name, scene);
  32909. }
  32910. mesh.id = parsedMesh.id;
  32911. if (BABYLON.Tags) {
  32912. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32913. }
  32914. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32915. if (parsedMesh.metadata !== undefined) {
  32916. mesh.metadata = parsedMesh.metadata;
  32917. }
  32918. if (parsedMesh.rotationQuaternion) {
  32919. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32920. }
  32921. else if (parsedMesh.rotation) {
  32922. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32923. }
  32924. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32925. if (parsedMesh.localMatrix) {
  32926. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32927. }
  32928. else if (parsedMesh.pivotMatrix) {
  32929. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32930. }
  32931. mesh.setEnabled(parsedMesh.isEnabled);
  32932. mesh.isVisible = parsedMesh.isVisible;
  32933. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32934. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32935. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32936. if (parsedMesh.applyFog !== undefined) {
  32937. mesh.applyFog = parsedMesh.applyFog;
  32938. }
  32939. if (parsedMesh.pickable !== undefined) {
  32940. mesh.isPickable = parsedMesh.pickable;
  32941. }
  32942. if (parsedMesh.alphaIndex !== undefined) {
  32943. mesh.alphaIndex = parsedMesh.alphaIndex;
  32944. }
  32945. mesh.receiveShadows = parsedMesh.receiveShadows;
  32946. mesh.billboardMode = parsedMesh.billboardMode;
  32947. if (parsedMesh.visibility !== undefined) {
  32948. mesh.visibility = parsedMesh.visibility;
  32949. }
  32950. mesh.checkCollisions = parsedMesh.checkCollisions;
  32951. if (parsedMesh.isBlocker !== undefined) {
  32952. mesh.isBlocker = parsedMesh.isBlocker;
  32953. }
  32954. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32955. // freezeWorldMatrix
  32956. if (parsedMesh.freezeWorldMatrix) {
  32957. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32958. }
  32959. // Parent
  32960. if (parsedMesh.parentId) {
  32961. mesh._waitingParentId = parsedMesh.parentId;
  32962. }
  32963. // Actions
  32964. if (parsedMesh.actions !== undefined) {
  32965. mesh._waitingActions = parsedMesh.actions;
  32966. }
  32967. // Overlay
  32968. if (parsedMesh.overlayAlpha !== undefined) {
  32969. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32970. }
  32971. if (parsedMesh.overlayColor !== undefined) {
  32972. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32973. }
  32974. if (parsedMesh.renderOverlay !== undefined) {
  32975. mesh.renderOverlay = parsedMesh.renderOverlay;
  32976. }
  32977. // Geometry
  32978. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32979. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32980. if (parsedMesh.delayLoadingFile) {
  32981. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32982. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32983. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32984. if (parsedMesh._binaryInfo) {
  32985. mesh._binaryInfo = parsedMesh._binaryInfo;
  32986. }
  32987. mesh._delayInfo = [];
  32988. if (parsedMesh.hasUVs) {
  32989. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32990. }
  32991. if (parsedMesh.hasUVs2) {
  32992. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32993. }
  32994. if (parsedMesh.hasUVs3) {
  32995. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32996. }
  32997. if (parsedMesh.hasUVs4) {
  32998. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32999. }
  33000. if (parsedMesh.hasUVs5) {
  33001. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33002. }
  33003. if (parsedMesh.hasUVs6) {
  33004. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33005. }
  33006. if (parsedMesh.hasColors) {
  33007. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33008. }
  33009. if (parsedMesh.hasMatricesIndices) {
  33010. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33011. }
  33012. if (parsedMesh.hasMatricesWeights) {
  33013. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33014. }
  33015. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33016. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33017. mesh._checkDelayState();
  33018. }
  33019. }
  33020. else {
  33021. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33022. }
  33023. // Material
  33024. if (parsedMesh.materialId) {
  33025. mesh.setMaterialByID(parsedMesh.materialId);
  33026. }
  33027. else {
  33028. mesh.material = null;
  33029. }
  33030. // Morph targets
  33031. if (parsedMesh.morphTargetManagerId > -1) {
  33032. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33033. }
  33034. // Skeleton
  33035. if (parsedMesh.skeletonId > -1) {
  33036. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33037. if (parsedMesh.numBoneInfluencers) {
  33038. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33039. }
  33040. }
  33041. // Animations
  33042. if (parsedMesh.animations) {
  33043. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33044. var parsedAnimation = parsedMesh.animations[animationIndex];
  33045. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33046. }
  33047. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33048. }
  33049. if (parsedMesh.autoAnimate) {
  33050. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33051. }
  33052. // Layer Mask
  33053. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33054. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33055. }
  33056. else {
  33057. mesh.layerMask = 0x0FFFFFFF;
  33058. }
  33059. // Physics
  33060. if (parsedMesh.physicsImpostor) {
  33061. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33062. mass: parsedMesh.physicsMass,
  33063. friction: parsedMesh.physicsFriction,
  33064. restitution: parsedMesh.physicsRestitution
  33065. }, scene);
  33066. }
  33067. // Instances
  33068. if (parsedMesh.instances) {
  33069. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33070. var parsedInstance = parsedMesh.instances[index];
  33071. var instance = mesh.createInstance(parsedInstance.name);
  33072. if (parsedInstance.id) {
  33073. instance.id = parsedInstance.id;
  33074. }
  33075. if (BABYLON.Tags) {
  33076. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33077. }
  33078. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33079. if (parsedInstance.parentId) {
  33080. instance._waitingParentId = parsedInstance.parentId;
  33081. }
  33082. if (parsedInstance.rotationQuaternion) {
  33083. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33084. }
  33085. else if (parsedInstance.rotation) {
  33086. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33087. }
  33088. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33089. instance.checkCollisions = mesh.checkCollisions;
  33090. if (parsedMesh.animations) {
  33091. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33092. parsedAnimation = parsedMesh.animations[animationIndex];
  33093. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33094. }
  33095. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33096. if (parsedMesh.autoAnimate) {
  33097. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33098. }
  33099. }
  33100. }
  33101. }
  33102. return mesh;
  33103. };
  33104. /**
  33105. * Creates a ribbon mesh.
  33106. * Please consider using the same method from the MeshBuilder class instead.
  33107. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33108. *
  33109. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33110. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33111. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33112. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33113. * 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.
  33114. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  33115. * 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
  33116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33117. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33119. */
  33120. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33121. if (closeArray === void 0) { closeArray = false; }
  33122. if (updatable === void 0) { updatable = false; }
  33123. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33124. pathArray: pathArray,
  33125. closeArray: closeArray,
  33126. closePath: closePath,
  33127. offset: offset,
  33128. updatable: updatable,
  33129. sideOrientation: sideOrientation,
  33130. instance: instance
  33131. }, scene);
  33132. };
  33133. /**
  33134. * Creates a plane polygonal mesh. By default, this is a disc.
  33135. * Please consider using the same method from the MeshBuilder class instead.
  33136. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33137. * 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.
  33138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33139. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33141. */
  33142. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33143. if (scene === void 0) { scene = null; }
  33144. var options = {
  33145. radius: radius,
  33146. tessellation: tessellation,
  33147. sideOrientation: sideOrientation,
  33148. updatable: updatable
  33149. };
  33150. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33151. };
  33152. /**
  33153. * Creates a box mesh.
  33154. * Please consider using the same method from the MeshBuilder class instead.
  33155. * The parameter `size` sets the size (float) of each box side (default 1).
  33156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33157. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33158. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33159. */
  33160. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33161. if (scene === void 0) { scene = null; }
  33162. var options = {
  33163. size: size,
  33164. sideOrientation: sideOrientation,
  33165. updatable: updatable
  33166. };
  33167. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33168. };
  33169. /**
  33170. * Creates a sphere mesh.
  33171. * Please consider using the same method from the MeshBuilder class instead.
  33172. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33173. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33174. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33175. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33176. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33177. */
  33178. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33179. var options = {
  33180. segments: segments,
  33181. diameterX: diameter,
  33182. diameterY: diameter,
  33183. diameterZ: diameter,
  33184. sideOrientation: sideOrientation,
  33185. updatable: updatable
  33186. };
  33187. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33188. };
  33189. /**
  33190. * Creates a cylinder or a cone mesh.
  33191. * Please consider using the same method from the MeshBuilder class instead.
  33192. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33193. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33194. * 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.
  33195. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33196. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33197. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33198. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33200. */
  33201. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33202. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33203. if (scene !== undefined) {
  33204. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33205. updatable = scene;
  33206. }
  33207. scene = subdivisions;
  33208. subdivisions = 1;
  33209. }
  33210. var options = {
  33211. height: height,
  33212. diameterTop: diameterTop,
  33213. diameterBottom: diameterBottom,
  33214. tessellation: tessellation,
  33215. subdivisions: subdivisions,
  33216. sideOrientation: sideOrientation,
  33217. updatable: updatable
  33218. };
  33219. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33220. };
  33221. // Torus (Code from SharpDX.org)
  33222. /**
  33223. * Creates a torus mesh.
  33224. * Please consider using the same method from the MeshBuilder class instead.
  33225. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33226. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33227. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33229. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33231. */
  33232. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33233. var options = {
  33234. diameter: diameter,
  33235. thickness: thickness,
  33236. tessellation: tessellation,
  33237. sideOrientation: sideOrientation,
  33238. updatable: updatable
  33239. };
  33240. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33241. };
  33242. /**
  33243. * Creates a torus knot mesh.
  33244. * Please consider using the same method from the MeshBuilder class instead.
  33245. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33246. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33247. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33248. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33249. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33250. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33252. */
  33253. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33254. var options = {
  33255. radius: radius,
  33256. tube: tube,
  33257. radialSegments: radialSegments,
  33258. tubularSegments: tubularSegments,
  33259. p: p,
  33260. q: q,
  33261. sideOrientation: sideOrientation,
  33262. updatable: updatable
  33263. };
  33264. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33265. };
  33266. /**
  33267. * Creates a line mesh.
  33268. * Please consider using the same method from the MeshBuilder class instead.
  33269. * 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.
  33270. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33271. * The parameter `points` is an array successive Vector3.
  33272. * 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
  33273. * When updating an instance, remember that only point positions can change, not the number of points.
  33274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33275. */
  33276. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33277. if (scene === void 0) { scene = null; }
  33278. if (updatable === void 0) { updatable = false; }
  33279. if (instance === void 0) { instance = null; }
  33280. var options = {
  33281. points: points,
  33282. updatable: updatable,
  33283. instance: instance
  33284. };
  33285. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33286. };
  33287. /**
  33288. * Creates a dashed line mesh.
  33289. * Please consider using the same method from the MeshBuilder class instead.
  33290. * 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.
  33291. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33292. * The parameter `points` is an array successive Vector3.
  33293. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33294. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33295. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33296. * 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
  33297. * When updating an instance, remember that only point positions can change, not the number of points.
  33298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33299. */
  33300. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33301. if (scene === void 0) { scene = null; }
  33302. var options = {
  33303. points: points,
  33304. dashSize: dashSize,
  33305. gapSize: gapSize,
  33306. dashNb: dashNb,
  33307. updatable: updatable,
  33308. instance: instance
  33309. };
  33310. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33311. };
  33312. /**
  33313. * Creates a polygon mesh.
  33314. * Please consider using the same method from the MeshBuilder class instead.
  33315. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33316. * 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.
  33317. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33318. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33319. * Remember you can only change the shape positions, not their number when updating a polygon.
  33320. */
  33321. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33322. var options = {
  33323. shape: shape,
  33324. holes: holes,
  33325. updatable: updatable,
  33326. sideOrientation: sideOrientation
  33327. };
  33328. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33329. };
  33330. /**
  33331. * Creates an extruded polygon mesh, with depth in the Y direction.
  33332. * Please consider using the same method from the MeshBuilder class instead.
  33333. */
  33334. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33335. var options = {
  33336. shape: shape,
  33337. holes: holes,
  33338. depth: depth,
  33339. updatable: updatable,
  33340. sideOrientation: sideOrientation
  33341. };
  33342. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33343. };
  33344. /**
  33345. * Creates an extruded shape mesh.
  33346. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33347. * Please consider using the same method from the MeshBuilder class instead.
  33348. *
  33349. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33350. * 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
  33351. * extruded along the Z axis.
  33352. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33353. * 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.
  33354. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33355. * 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
  33356. * 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
  33357. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33359. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33361. */
  33362. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33363. if (scene === void 0) { scene = null; }
  33364. var options = {
  33365. shape: shape,
  33366. path: path,
  33367. scale: scale,
  33368. rotation: rotation,
  33369. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33370. sideOrientation: sideOrientation,
  33371. instance: instance,
  33372. updatable: updatable
  33373. };
  33374. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33375. };
  33376. /**
  33377. * Creates an custom extruded shape mesh.
  33378. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33379. * Please consider using the same method from the MeshBuilder class instead.
  33380. *
  33381. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33382. * 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
  33383. * extruded along the Z axis.
  33384. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33385. * 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
  33386. * and the distance of this point from the begining of the path :
  33387. * ```javascript
  33388. * var rotationFunction = function(i, distance) {
  33389. * // do things
  33390. * return rotationValue; }
  33391. * ```
  33392. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33393. * 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
  33394. * and the distance of this point from the begining of the path :
  33395. * ```javascript
  33396. * var scaleFunction = function(i, distance) {
  33397. * // do things
  33398. * return scaleValue;}
  33399. * ```
  33400. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33401. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33402. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33403. * 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
  33404. * 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
  33405. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33407. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33409. */
  33410. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33411. var options = {
  33412. shape: shape,
  33413. path: path,
  33414. scaleFunction: scaleFunction,
  33415. rotationFunction: rotationFunction,
  33416. ribbonCloseArray: ribbonCloseArray,
  33417. ribbonClosePath: ribbonClosePath,
  33418. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33419. sideOrientation: sideOrientation,
  33420. instance: instance,
  33421. updatable: updatable
  33422. };
  33423. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33424. };
  33425. /**
  33426. * Creates lathe mesh.
  33427. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33428. * Please consider using the same method from the MeshBuilder class instead.
  33429. * 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
  33430. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33431. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33432. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33433. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33434. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33435. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33436. */
  33437. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33438. var options = {
  33439. shape: shape,
  33440. radius: radius,
  33441. tessellation: tessellation,
  33442. sideOrientation: sideOrientation,
  33443. updatable: updatable
  33444. };
  33445. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33446. };
  33447. /**
  33448. * Creates a plane mesh.
  33449. * Please consider using the same method from the MeshBuilder class instead.
  33450. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33451. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33452. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33453. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33454. */
  33455. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33456. var options = {
  33457. size: size,
  33458. width: size,
  33459. height: size,
  33460. sideOrientation: sideOrientation,
  33461. updatable: updatable
  33462. };
  33463. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33464. };
  33465. /**
  33466. * Creates a ground mesh.
  33467. * Please consider using the same method from the MeshBuilder class instead.
  33468. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33469. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33471. */
  33472. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33473. var options = {
  33474. width: width,
  33475. height: height,
  33476. subdivisions: subdivisions,
  33477. updatable: updatable
  33478. };
  33479. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33480. };
  33481. /**
  33482. * Creates a tiled ground mesh.
  33483. * Please consider using the same method from the MeshBuilder class instead.
  33484. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33485. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33486. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33487. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33488. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33489. * numbers of subdivisions on the ground width and height of each tile.
  33490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33491. */
  33492. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33493. var options = {
  33494. xmin: xmin,
  33495. zmin: zmin,
  33496. xmax: xmax,
  33497. zmax: zmax,
  33498. subdivisions: subdivisions,
  33499. precision: precision,
  33500. updatable: updatable
  33501. };
  33502. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33503. };
  33504. /**
  33505. * Creates a ground mesh from a height map.
  33506. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33507. * Please consider using the same method from the MeshBuilder class instead.
  33508. * The parameter `url` sets the URL of the height map image resource.
  33509. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33510. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33511. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33512. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33513. * 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).
  33514. * This function is passed the newly built mesh :
  33515. * ```javascript
  33516. * function(mesh) { // do things
  33517. * return; }
  33518. * ```
  33519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33520. */
  33521. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33522. var options = {
  33523. width: width,
  33524. height: height,
  33525. subdivisions: subdivisions,
  33526. minHeight: minHeight,
  33527. maxHeight: maxHeight,
  33528. updatable: updatable,
  33529. onReady: onReady
  33530. };
  33531. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33532. };
  33533. /**
  33534. * Creates a tube mesh.
  33535. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33536. * Please consider using the same method from the MeshBuilder class instead.
  33537. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33538. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33539. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33540. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33541. * 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.
  33542. * It must return a radius value (positive float) :
  33543. * ```javascript
  33544. * var radiusFunction = function(i, distance) {
  33545. * // do things
  33546. * return radius; }
  33547. * ```
  33548. * 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
  33549. * 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
  33550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33551. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33555. var options = {
  33556. path: path,
  33557. radius: radius,
  33558. tessellation: tessellation,
  33559. radiusFunction: radiusFunction,
  33560. arc: 1,
  33561. cap: cap,
  33562. updatable: updatable,
  33563. sideOrientation: sideOrientation,
  33564. instance: instance
  33565. };
  33566. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33567. };
  33568. /**
  33569. * Creates a polyhedron mesh.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. * 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
  33572. * to choose the wanted type.
  33573. * The parameter `size` (positive float, default 1) sets the polygon size.
  33574. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33575. * 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`.
  33576. * 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
  33577. * 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)`).
  33578. * 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
  33579. * 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.
  33580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33581. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33583. */
  33584. Mesh.CreatePolyhedron = function (name, options, scene) {
  33585. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33586. };
  33587. /**
  33588. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33589. * Please consider using the same method from the MeshBuilder class instead.
  33590. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33591. * 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`).
  33592. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33593. * 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.
  33594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33595. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33597. */
  33598. Mesh.CreateIcoSphere = function (name, options, scene) {
  33599. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33600. };
  33601. /**
  33602. * Creates a decal mesh.
  33603. * Please consider using the same method from the MeshBuilder class instead.
  33604. * 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.
  33605. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33606. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33607. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33608. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33609. */
  33610. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33611. var options = {
  33612. position: position,
  33613. normal: normal,
  33614. size: size,
  33615. angle: angle
  33616. };
  33617. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33618. };
  33619. // Skeletons
  33620. /**
  33621. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33622. */
  33623. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33624. if (!this._sourcePositions) {
  33625. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33626. if (!source) {
  33627. return this._sourcePositions;
  33628. }
  33629. this._sourcePositions = new Float32Array(source);
  33630. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33631. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33632. }
  33633. }
  33634. return this._sourcePositions;
  33635. };
  33636. /**
  33637. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33638. */
  33639. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33640. if (!this._sourceNormals) {
  33641. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33642. if (!source) {
  33643. return this._sourceNormals;
  33644. }
  33645. this._sourceNormals = new Float32Array(source);
  33646. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33647. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33648. }
  33649. }
  33650. return this._sourceNormals;
  33651. };
  33652. /**
  33653. * Updates the vertex buffer by applying transformation from the bones.
  33654. * Returns the Mesh.
  33655. *
  33656. * @param {skeleton} skeleton to apply
  33657. */
  33658. Mesh.prototype.applySkeleton = function (skeleton) {
  33659. if (!this.geometry) {
  33660. return this;
  33661. }
  33662. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33663. return this;
  33664. }
  33665. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33666. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33667. return this;
  33668. }
  33669. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33670. return this;
  33671. }
  33672. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33673. return this;
  33674. }
  33675. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33676. return this;
  33677. }
  33678. if (!this._sourcePositions) {
  33679. var submeshes = this.subMeshes.slice();
  33680. this.setPositionsForCPUSkinning();
  33681. this.subMeshes = submeshes;
  33682. }
  33683. if (!this._sourceNormals) {
  33684. this.setNormalsForCPUSkinning();
  33685. }
  33686. // positionsData checks for not being Float32Array will only pass at most once
  33687. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33688. if (!positionsData) {
  33689. return this;
  33690. }
  33691. if (!(positionsData instanceof Float32Array)) {
  33692. positionsData = new Float32Array(positionsData);
  33693. }
  33694. // normalsData checks for not being Float32Array will only pass at most once
  33695. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33696. if (!normalsData) {
  33697. return this;
  33698. }
  33699. if (!(normalsData instanceof Float32Array)) {
  33700. normalsData = new Float32Array(normalsData);
  33701. }
  33702. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33703. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33704. if (!matricesWeightsData || !matricesIndicesData) {
  33705. return this;
  33706. }
  33707. var needExtras = this.numBoneInfluencers > 4;
  33708. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33709. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33710. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33711. var tempVector3 = BABYLON.Vector3.Zero();
  33712. var finalMatrix = new BABYLON.Matrix();
  33713. var tempMatrix = new BABYLON.Matrix();
  33714. var matWeightIdx = 0;
  33715. var inf;
  33716. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33717. var weight;
  33718. for (inf = 0; inf < 4; inf++) {
  33719. weight = matricesWeightsData[matWeightIdx + inf];
  33720. if (weight > 0) {
  33721. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33722. finalMatrix.addToSelf(tempMatrix);
  33723. }
  33724. }
  33725. if (needExtras) {
  33726. for (inf = 0; inf < 4; inf++) {
  33727. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33728. if (weight > 0) {
  33729. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33730. finalMatrix.addToSelf(tempMatrix);
  33731. }
  33732. }
  33733. }
  33734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33735. tempVector3.toArray(positionsData, index);
  33736. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33737. tempVector3.toArray(normalsData, index);
  33738. finalMatrix.reset();
  33739. }
  33740. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33741. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33742. return this;
  33743. };
  33744. // Tools
  33745. /**
  33746. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33747. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33748. */
  33749. Mesh.MinMax = function (meshes) {
  33750. var minVector = null;
  33751. var maxVector = null;
  33752. meshes.forEach(function (mesh, index, array) {
  33753. var boundingInfo = mesh.getBoundingInfo();
  33754. var boundingBox = boundingInfo.boundingBox;
  33755. if (!minVector || !maxVector) {
  33756. minVector = boundingBox.minimumWorld;
  33757. maxVector = boundingBox.maximumWorld;
  33758. }
  33759. else {
  33760. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33761. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33762. }
  33763. });
  33764. if (!minVector || !maxVector) {
  33765. return {
  33766. min: BABYLON.Vector3.Zero(),
  33767. max: BABYLON.Vector3.Zero()
  33768. };
  33769. }
  33770. return {
  33771. min: minVector,
  33772. max: maxVector
  33773. };
  33774. };
  33775. /**
  33776. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33777. */
  33778. Mesh.Center = function (meshesOrMinMaxVector) {
  33779. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33780. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33781. };
  33782. /**
  33783. * Merge the array of meshes into a single mesh for performance reasons.
  33784. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33785. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33786. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33787. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33788. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33789. */
  33790. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33791. if (disposeSource === void 0) { disposeSource = true; }
  33792. var index;
  33793. if (!allow32BitsIndices) {
  33794. var totalVertices = 0;
  33795. // Counting vertices
  33796. for (index = 0; index < meshes.length; index++) {
  33797. if (meshes[index]) {
  33798. totalVertices += meshes[index].getTotalVertices();
  33799. if (totalVertices > 65536) {
  33800. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33801. return null;
  33802. }
  33803. }
  33804. }
  33805. }
  33806. // Merge
  33807. var vertexData = null;
  33808. var otherVertexData;
  33809. var indiceArray = new Array();
  33810. var source = null;
  33811. for (index = 0; index < meshes.length; index++) {
  33812. if (meshes[index]) {
  33813. meshes[index].computeWorldMatrix(true);
  33814. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33815. otherVertexData.transform(meshes[index].getWorldMatrix());
  33816. if (vertexData) {
  33817. vertexData.merge(otherVertexData);
  33818. }
  33819. else {
  33820. vertexData = otherVertexData;
  33821. source = meshes[index];
  33822. }
  33823. if (subdivideWithSubMeshes) {
  33824. indiceArray.push(meshes[index].getTotalIndices());
  33825. }
  33826. }
  33827. }
  33828. source = source;
  33829. if (!meshSubclass) {
  33830. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33831. }
  33832. vertexData.applyToMesh(meshSubclass);
  33833. // Setting properties
  33834. meshSubclass.material = source.material;
  33835. meshSubclass.checkCollisions = source.checkCollisions;
  33836. // Cleaning
  33837. if (disposeSource) {
  33838. for (index = 0; index < meshes.length; index++) {
  33839. if (meshes[index]) {
  33840. meshes[index].dispose();
  33841. }
  33842. }
  33843. }
  33844. // Subdivide
  33845. if (subdivideWithSubMeshes) {
  33846. //-- removal of global submesh
  33847. meshSubclass.releaseSubMeshes();
  33848. index = 0;
  33849. var offset = 0;
  33850. //-- apply subdivision according to index table
  33851. while (index < indiceArray.length) {
  33852. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33853. offset += indiceArray[index];
  33854. index++;
  33855. }
  33856. }
  33857. return meshSubclass;
  33858. };
  33859. // Consts
  33860. Mesh._FRONTSIDE = 0;
  33861. Mesh._BACKSIDE = 1;
  33862. Mesh._DOUBLESIDE = 2;
  33863. Mesh._DEFAULTSIDE = 0;
  33864. Mesh._NO_CAP = 0;
  33865. Mesh._CAP_START = 1;
  33866. Mesh._CAP_END = 2;
  33867. Mesh._CAP_ALL = 3;
  33868. return Mesh;
  33869. }(BABYLON.AbstractMesh));
  33870. BABYLON.Mesh = Mesh;
  33871. })(BABYLON || (BABYLON = {}));
  33872. //# sourceMappingURL=babylon.mesh.js.map
  33873. var BABYLON;
  33874. (function (BABYLON) {
  33875. var BaseSubMesh = /** @class */ (function () {
  33876. function BaseSubMesh() {
  33877. }
  33878. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33879. get: function () {
  33880. return this._materialEffect;
  33881. },
  33882. enumerable: true,
  33883. configurable: true
  33884. });
  33885. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33886. if (defines === void 0) { defines = null; }
  33887. if (this._materialEffect === effect) {
  33888. if (!effect) {
  33889. this._materialDefines = null;
  33890. }
  33891. return;
  33892. }
  33893. this._materialDefines = defines;
  33894. this._materialEffect = effect;
  33895. };
  33896. return BaseSubMesh;
  33897. }());
  33898. BABYLON.BaseSubMesh = BaseSubMesh;
  33899. var SubMesh = /** @class */ (function (_super) {
  33900. __extends(SubMesh, _super);
  33901. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33902. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33903. var _this = _super.call(this) || this;
  33904. _this.materialIndex = materialIndex;
  33905. _this.verticesStart = verticesStart;
  33906. _this.verticesCount = verticesCount;
  33907. _this.indexStart = indexStart;
  33908. _this.indexCount = indexCount;
  33909. _this._renderId = 0;
  33910. _this._mesh = mesh;
  33911. _this._renderingMesh = renderingMesh || mesh;
  33912. mesh.subMeshes.push(_this);
  33913. _this._trianglePlanes = [];
  33914. _this._id = mesh.subMeshes.length - 1;
  33915. if (createBoundingBox) {
  33916. _this.refreshBoundingInfo();
  33917. mesh.computeWorldMatrix(true);
  33918. }
  33919. return _this;
  33920. }
  33921. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33922. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33923. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33924. };
  33925. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33926. get: function () {
  33927. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33928. },
  33929. enumerable: true,
  33930. configurable: true
  33931. });
  33932. /**
  33933. * Returns the submesh BoudingInfo object.
  33934. */
  33935. SubMesh.prototype.getBoundingInfo = function () {
  33936. if (this.IsGlobal) {
  33937. return this._mesh.getBoundingInfo();
  33938. }
  33939. return this._boundingInfo;
  33940. };
  33941. /**
  33942. * Sets the submesh BoundingInfo.
  33943. * Return the SubMesh.
  33944. */
  33945. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33946. this._boundingInfo = boundingInfo;
  33947. return this;
  33948. };
  33949. /**
  33950. * Returns the mesh of the current submesh.
  33951. */
  33952. SubMesh.prototype.getMesh = function () {
  33953. return this._mesh;
  33954. };
  33955. /**
  33956. * Returns the rendering mesh of the submesh.
  33957. */
  33958. SubMesh.prototype.getRenderingMesh = function () {
  33959. return this._renderingMesh;
  33960. };
  33961. /**
  33962. * Returns the submesh material.
  33963. */
  33964. SubMesh.prototype.getMaterial = function () {
  33965. var rootMaterial = this._renderingMesh.material;
  33966. if (rootMaterial === null || rootMaterial === undefined) {
  33967. return this._mesh.getScene().defaultMaterial;
  33968. }
  33969. else if (rootMaterial.getSubMaterial) {
  33970. var multiMaterial = rootMaterial;
  33971. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33972. if (this._currentMaterial !== effectiveMaterial) {
  33973. this._currentMaterial = effectiveMaterial;
  33974. this._materialDefines = null;
  33975. }
  33976. return effectiveMaterial;
  33977. }
  33978. return rootMaterial;
  33979. };
  33980. // Methods
  33981. /**
  33982. * Sets a new updated BoundingInfo object to the submesh.
  33983. * Returns the SubMesh.
  33984. */
  33985. SubMesh.prototype.refreshBoundingInfo = function () {
  33986. this._lastColliderWorldVertices = null;
  33987. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33988. return this;
  33989. }
  33990. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33991. if (!data) {
  33992. this._boundingInfo = this._mesh.getBoundingInfo();
  33993. return this;
  33994. }
  33995. var indices = this._renderingMesh.getIndices();
  33996. var extend;
  33997. //is this the only submesh?
  33998. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33999. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34000. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34001. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34002. }
  34003. else {
  34004. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34005. }
  34006. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34007. return this;
  34008. };
  34009. SubMesh.prototype._checkCollision = function (collider) {
  34010. var boundingInfo = this.getBoundingInfo();
  34011. return boundingInfo._checkCollision(collider);
  34012. };
  34013. /**
  34014. * Updates the submesh BoundingInfo.
  34015. * Returns the Submesh.
  34016. */
  34017. SubMesh.prototype.updateBoundingInfo = function (world) {
  34018. var boundingInfo = this.getBoundingInfo();
  34019. if (!boundingInfo) {
  34020. this.refreshBoundingInfo();
  34021. boundingInfo = this.getBoundingInfo();
  34022. }
  34023. boundingInfo.update(world);
  34024. return this;
  34025. };
  34026. /**
  34027. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34028. * Boolean returned.
  34029. */
  34030. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34031. var boundingInfo = this.getBoundingInfo();
  34032. if (!boundingInfo) {
  34033. return false;
  34034. }
  34035. return boundingInfo.isInFrustum(frustumPlanes);
  34036. };
  34037. /**
  34038. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34039. * Boolean returned.
  34040. */
  34041. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34042. var boundingInfo = this.getBoundingInfo();
  34043. if (!boundingInfo) {
  34044. return false;
  34045. }
  34046. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34047. };
  34048. /**
  34049. * Renders the submesh.
  34050. * Returns it.
  34051. */
  34052. SubMesh.prototype.render = function (enableAlphaMode) {
  34053. this._renderingMesh.render(this, enableAlphaMode);
  34054. return this;
  34055. };
  34056. /**
  34057. * Returns a new Index Buffer.
  34058. * Type returned : WebGLBuffer.
  34059. */
  34060. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34061. if (!this._linesIndexBuffer) {
  34062. var linesIndices = [];
  34063. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34064. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34065. }
  34066. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34067. this.linesIndexCount = linesIndices.length;
  34068. }
  34069. return this._linesIndexBuffer;
  34070. };
  34071. /**
  34072. * True is the passed Ray intersects the submesh bounding box.
  34073. * Boolean returned.
  34074. */
  34075. SubMesh.prototype.canIntersects = function (ray) {
  34076. var boundingInfo = this.getBoundingInfo();
  34077. if (!boundingInfo) {
  34078. return false;
  34079. }
  34080. return ray.intersectsBox(boundingInfo.boundingBox);
  34081. };
  34082. /**
  34083. * Returns an object IntersectionInfo.
  34084. */
  34085. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34086. var intersectInfo = null;
  34087. var material = this.getMaterial();
  34088. if (!material) {
  34089. return null;
  34090. }
  34091. switch (material.fillMode) {
  34092. case BABYLON.Material.PointListDrawMode:
  34093. case BABYLON.Material.LineListDrawMode:
  34094. case BABYLON.Material.LineLoopDrawMode:
  34095. case BABYLON.Material.LineStripDrawMode:
  34096. case BABYLON.Material.TriangleFanDrawMode:
  34097. case BABYLON.Material.TriangleStripDrawMode:
  34098. return null;
  34099. }
  34100. // LineMesh first as it's also a Mesh...
  34101. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34102. var lineMesh = this._mesh;
  34103. // Line test
  34104. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34105. var p0 = positions[indices[index]];
  34106. var p1 = positions[indices[index + 1]];
  34107. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34108. if (length < 0) {
  34109. continue;
  34110. }
  34111. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34112. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34113. if (fastCheck) {
  34114. break;
  34115. }
  34116. }
  34117. }
  34118. }
  34119. else {
  34120. // Triangles test
  34121. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34122. var p0 = positions[indices[index]];
  34123. var p1 = positions[indices[index + 1]];
  34124. var p2 = positions[indices[index + 2]];
  34125. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34126. if (currentIntersectInfo) {
  34127. if (currentIntersectInfo.distance < 0) {
  34128. continue;
  34129. }
  34130. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34131. intersectInfo = currentIntersectInfo;
  34132. intersectInfo.faceId = index / 3;
  34133. if (fastCheck) {
  34134. break;
  34135. }
  34136. }
  34137. }
  34138. }
  34139. }
  34140. return intersectInfo;
  34141. };
  34142. SubMesh.prototype._rebuild = function () {
  34143. if (this._linesIndexBuffer) {
  34144. this._linesIndexBuffer = null;
  34145. }
  34146. };
  34147. // Clone
  34148. /**
  34149. * Creates a new Submesh from the passed Mesh.
  34150. */
  34151. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34152. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34153. if (!this.IsGlobal) {
  34154. var boundingInfo = this.getBoundingInfo();
  34155. if (!boundingInfo) {
  34156. return result;
  34157. }
  34158. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34159. }
  34160. return result;
  34161. };
  34162. // Dispose
  34163. /**
  34164. * Disposes the Submesh.
  34165. * Returns nothing.
  34166. */
  34167. SubMesh.prototype.dispose = function () {
  34168. if (this._linesIndexBuffer) {
  34169. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34170. this._linesIndexBuffer = null;
  34171. }
  34172. // Remove from mesh
  34173. var index = this._mesh.subMeshes.indexOf(this);
  34174. this._mesh.subMeshes.splice(index, 1);
  34175. };
  34176. // Statics
  34177. /**
  34178. * Creates a new Submesh from the passed parameters :
  34179. * - materialIndex (integer) : the index of the main mesh material.
  34180. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34181. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34182. * - mesh (Mesh) : the main mesh to create the submesh from.
  34183. * - renderingMesh (optional Mesh) : rendering mesh.
  34184. */
  34185. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34186. var minVertexIndex = Number.MAX_VALUE;
  34187. var maxVertexIndex = -Number.MAX_VALUE;
  34188. renderingMesh = (renderingMesh || mesh);
  34189. var indices = renderingMesh.getIndices();
  34190. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34191. var vertexIndex = indices[index];
  34192. if (vertexIndex < minVertexIndex)
  34193. minVertexIndex = vertexIndex;
  34194. if (vertexIndex > maxVertexIndex)
  34195. maxVertexIndex = vertexIndex;
  34196. }
  34197. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34198. };
  34199. return SubMesh;
  34200. }(BaseSubMesh));
  34201. BABYLON.SubMesh = SubMesh;
  34202. })(BABYLON || (BABYLON = {}));
  34203. //# sourceMappingURL=babylon.subMesh.js.map
  34204. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34205. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34206. s = arguments[i];
  34207. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34208. t[p] = s[p];
  34209. }
  34210. return t;
  34211. };
  34212. var BABYLON;
  34213. (function (BABYLON) {
  34214. /**
  34215. * Manages the defines for the Material
  34216. */
  34217. var MaterialDefines = /** @class */ (function () {
  34218. function MaterialDefines() {
  34219. this._isDirty = true;
  34220. /** @hidden */
  34221. this._areLightsDirty = true;
  34222. /** @hidden */
  34223. this._areAttributesDirty = true;
  34224. /** @hidden */
  34225. this._areTexturesDirty = true;
  34226. /** @hidden */
  34227. this._areFresnelDirty = true;
  34228. /** @hidden */
  34229. this._areMiscDirty = true;
  34230. /** @hidden */
  34231. this._areImageProcessingDirty = true;
  34232. /** @hidden */
  34233. this._normals = false;
  34234. /** @hidden */
  34235. this._uvs = false;
  34236. /** @hidden */
  34237. this._needNormals = false;
  34238. /** @hidden */
  34239. this._needUVs = false;
  34240. }
  34241. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34242. /**
  34243. * Specifies if the material needs to be re-calculated
  34244. */
  34245. get: function () {
  34246. return this._isDirty;
  34247. },
  34248. enumerable: true,
  34249. configurable: true
  34250. });
  34251. /**
  34252. * Marks the material to indicate that it has been re-calculated
  34253. */
  34254. MaterialDefines.prototype.markAsProcessed = function () {
  34255. this._isDirty = false;
  34256. this._areAttributesDirty = false;
  34257. this._areTexturesDirty = false;
  34258. this._areFresnelDirty = false;
  34259. this._areLightsDirty = false;
  34260. this._areMiscDirty = false;
  34261. this._areImageProcessingDirty = false;
  34262. };
  34263. /**
  34264. * Marks the material to indicate that it needs to be re-calculated
  34265. */
  34266. MaterialDefines.prototype.markAsUnprocessed = function () {
  34267. this._isDirty = true;
  34268. };
  34269. /**
  34270. * Marks the material to indicate all of its defines need to be re-calculated
  34271. */
  34272. MaterialDefines.prototype.markAllAsDirty = function () {
  34273. this._areTexturesDirty = true;
  34274. this._areAttributesDirty = true;
  34275. this._areLightsDirty = true;
  34276. this._areFresnelDirty = true;
  34277. this._areMiscDirty = true;
  34278. this._areImageProcessingDirty = true;
  34279. this._isDirty = true;
  34280. };
  34281. /**
  34282. * Marks the material to indicate that image processing needs to be re-calculated
  34283. */
  34284. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34285. this._areImageProcessingDirty = true;
  34286. this._isDirty = true;
  34287. };
  34288. /**
  34289. * Marks the material to indicate the lights need to be re-calculated
  34290. */
  34291. MaterialDefines.prototype.markAsLightDirty = function () {
  34292. this._areLightsDirty = true;
  34293. this._isDirty = true;
  34294. };
  34295. /**
  34296. * Marks the attribute state as changed
  34297. */
  34298. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34299. this._areAttributesDirty = true;
  34300. this._isDirty = true;
  34301. };
  34302. /**
  34303. * Marks the texture state as changed
  34304. */
  34305. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34306. this._areTexturesDirty = true;
  34307. this._isDirty = true;
  34308. };
  34309. /**
  34310. * Marks the fresnel state as changed
  34311. */
  34312. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34313. this._areFresnelDirty = true;
  34314. this._isDirty = true;
  34315. };
  34316. /**
  34317. * Marks the misc state as changed
  34318. */
  34319. MaterialDefines.prototype.markAsMiscDirty = function () {
  34320. this._areMiscDirty = true;
  34321. this._isDirty = true;
  34322. };
  34323. /**
  34324. * Rebuilds the material defines
  34325. */
  34326. MaterialDefines.prototype.rebuild = function () {
  34327. if (this._keys) {
  34328. delete this._keys;
  34329. }
  34330. this._keys = [];
  34331. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34332. var key = _a[_i];
  34333. if (key[0] === "_") {
  34334. continue;
  34335. }
  34336. this._keys.push(key);
  34337. }
  34338. };
  34339. /**
  34340. * Specifies if two material defines are equal
  34341. * @param other - A material define instance to compare to
  34342. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34343. */
  34344. MaterialDefines.prototype.isEqual = function (other) {
  34345. if (this._keys.length !== other._keys.length) {
  34346. return false;
  34347. }
  34348. for (var index = 0; index < this._keys.length; index++) {
  34349. var prop = this._keys[index];
  34350. if (this[prop] !== other[prop]) {
  34351. return false;
  34352. }
  34353. }
  34354. return true;
  34355. };
  34356. /**
  34357. * Clones this instance's defines to another instance
  34358. * @param other - material defines to clone values to
  34359. */
  34360. MaterialDefines.prototype.cloneTo = function (other) {
  34361. if (this._keys.length !== other._keys.length) {
  34362. other._keys = this._keys.slice(0);
  34363. }
  34364. for (var index = 0; index < this._keys.length; index++) {
  34365. var prop = this._keys[index];
  34366. other[prop] = this[prop];
  34367. }
  34368. };
  34369. /**
  34370. * Resets the material define values
  34371. */
  34372. MaterialDefines.prototype.reset = function () {
  34373. for (var index = 0; index < this._keys.length; index++) {
  34374. var prop = this._keys[index];
  34375. var type = typeof this[prop];
  34376. switch (type) {
  34377. case "number":
  34378. this[prop] = 0;
  34379. break;
  34380. case "string":
  34381. this[prop] = "";
  34382. break;
  34383. default:
  34384. this[prop] = false;
  34385. break;
  34386. }
  34387. }
  34388. };
  34389. /**
  34390. * Converts the material define values to a string
  34391. * @returns - String of material define information
  34392. */
  34393. MaterialDefines.prototype.toString = function () {
  34394. var result = "";
  34395. for (var index = 0; index < this._keys.length; index++) {
  34396. var prop = this._keys[index];
  34397. var value = this[prop];
  34398. var type = typeof value;
  34399. switch (type) {
  34400. case "number":
  34401. case "string":
  34402. result += "#define " + prop + " " + value + "\n";
  34403. break;
  34404. default:
  34405. if (value) {
  34406. result += "#define " + prop + "\n";
  34407. }
  34408. break;
  34409. }
  34410. }
  34411. return result;
  34412. };
  34413. return MaterialDefines;
  34414. }());
  34415. BABYLON.MaterialDefines = MaterialDefines;
  34416. /**
  34417. * Base class for the main features of a material in Babylon.js
  34418. */
  34419. var Material = /** @class */ (function () {
  34420. /**
  34421. * Creates a material instance
  34422. * @param name defines the name of the material
  34423. * @param scene defines the scene to reference
  34424. * @param doNotAdd specifies if the material should be added to the scene
  34425. */
  34426. function Material(name, scene, doNotAdd) {
  34427. /**
  34428. * Specifies if the ready state should be checked on each call
  34429. */
  34430. this.checkReadyOnEveryCall = false;
  34431. /**
  34432. * Specifies if the ready state should be checked once
  34433. */
  34434. this.checkReadyOnlyOnce = false;
  34435. /**
  34436. * The state of the material
  34437. */
  34438. this.state = "";
  34439. /**
  34440. * The alpha value of the material
  34441. */
  34442. this._alpha = 1.0;
  34443. /**
  34444. * Specifies if back face culling is enabled
  34445. */
  34446. this._backFaceCulling = true;
  34447. /**
  34448. * Specifies if the material should be serialized
  34449. */
  34450. this.doNotSerialize = false;
  34451. /**
  34452. * Specifies if the effect should be stored on sub meshes
  34453. */
  34454. this.storeEffectOnSubMeshes = false;
  34455. /**
  34456. * An event triggered when the material is disposed
  34457. */
  34458. this.onDisposeObservable = new BABYLON.Observable();
  34459. /**
  34460. * An event triggered when the material is bound
  34461. */
  34462. this.onBindObservable = new BABYLON.Observable();
  34463. /**
  34464. * An event triggered when the material is unbound
  34465. */
  34466. this.onUnBindObservable = new BABYLON.Observable();
  34467. /**
  34468. * Stores the value of the alpha mode
  34469. */
  34470. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34471. /**
  34472. * Stores the state of the need depth pre-pass value
  34473. */
  34474. this._needDepthPrePass = false;
  34475. /**
  34476. * Specifies if depth writing should be disabled
  34477. */
  34478. this.disableDepthWrite = false;
  34479. /**
  34480. * Specifies if depth writing should be forced
  34481. */
  34482. this.forceDepthWrite = false;
  34483. /**
  34484. * Specifies if there should be a separate pass for culling
  34485. */
  34486. this.separateCullingPass = false;
  34487. /**
  34488. * Stores the state specifing if fog should be enabled
  34489. */
  34490. this._fogEnabled = true;
  34491. /**
  34492. * Stores the size of points
  34493. */
  34494. this.pointSize = 1.0;
  34495. /**
  34496. * Stores the z offset value
  34497. */
  34498. this.zOffset = 0;
  34499. /**
  34500. * Specifies if the material was previously ready
  34501. */
  34502. this._wasPreviouslyReady = false;
  34503. /**
  34504. * Stores the fill mode state
  34505. */
  34506. this._fillMode = Material.TriangleFillMode;
  34507. this.name = name;
  34508. this.id = name || BABYLON.Tools.RandomId();
  34509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34510. this.uniqueId = this._scene.getUniqueId();
  34511. if (this._scene.useRightHandedSystem) {
  34512. this.sideOrientation = Material.ClockWiseSideOrientation;
  34513. }
  34514. else {
  34515. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34516. }
  34517. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34518. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34519. if (!doNotAdd) {
  34520. this._scene.materials.push(this);
  34521. }
  34522. }
  34523. Object.defineProperty(Material, "TriangleFillMode", {
  34524. /**
  34525. * Returns the triangle fill mode
  34526. */
  34527. get: function () {
  34528. return Material._TriangleFillMode;
  34529. },
  34530. enumerable: true,
  34531. configurable: true
  34532. });
  34533. Object.defineProperty(Material, "WireFrameFillMode", {
  34534. /**
  34535. * Returns the wireframe mode
  34536. */
  34537. get: function () {
  34538. return Material._WireFrameFillMode;
  34539. },
  34540. enumerable: true,
  34541. configurable: true
  34542. });
  34543. Object.defineProperty(Material, "PointFillMode", {
  34544. /**
  34545. * Returns the point fill mode
  34546. */
  34547. get: function () {
  34548. return Material._PointFillMode;
  34549. },
  34550. enumerable: true,
  34551. configurable: true
  34552. });
  34553. Object.defineProperty(Material, "PointListDrawMode", {
  34554. /**
  34555. * Returns the point list draw mode
  34556. */
  34557. get: function () {
  34558. return Material._PointListDrawMode;
  34559. },
  34560. enumerable: true,
  34561. configurable: true
  34562. });
  34563. Object.defineProperty(Material, "LineListDrawMode", {
  34564. /**
  34565. * Returns the line list draw mode
  34566. */
  34567. get: function () {
  34568. return Material._LineListDrawMode;
  34569. },
  34570. enumerable: true,
  34571. configurable: true
  34572. });
  34573. Object.defineProperty(Material, "LineLoopDrawMode", {
  34574. /**
  34575. * Returns the line loop draw mode
  34576. */
  34577. get: function () {
  34578. return Material._LineLoopDrawMode;
  34579. },
  34580. enumerable: true,
  34581. configurable: true
  34582. });
  34583. Object.defineProperty(Material, "LineStripDrawMode", {
  34584. /**
  34585. * Returns the line strip draw mode
  34586. */
  34587. get: function () {
  34588. return Material._LineStripDrawMode;
  34589. },
  34590. enumerable: true,
  34591. configurable: true
  34592. });
  34593. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34594. /**
  34595. * Returns the triangle strip draw mode
  34596. */
  34597. get: function () {
  34598. return Material._TriangleStripDrawMode;
  34599. },
  34600. enumerable: true,
  34601. configurable: true
  34602. });
  34603. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34604. /**
  34605. * Returns the triangle fan draw mode
  34606. */
  34607. get: function () {
  34608. return Material._TriangleFanDrawMode;
  34609. },
  34610. enumerable: true,
  34611. configurable: true
  34612. });
  34613. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34614. /**
  34615. * Returns the clock-wise side orientation
  34616. */
  34617. get: function () {
  34618. return Material._ClockWiseSideOrientation;
  34619. },
  34620. enumerable: true,
  34621. configurable: true
  34622. });
  34623. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34624. /**
  34625. * Returns the counter clock-wise side orientation
  34626. */
  34627. get: function () {
  34628. return Material._CounterClockWiseSideOrientation;
  34629. },
  34630. enumerable: true,
  34631. configurable: true
  34632. });
  34633. Object.defineProperty(Material, "TextureDirtyFlag", {
  34634. /**
  34635. * Returns the dirty texture flag value
  34636. */
  34637. get: function () {
  34638. return Material._TextureDirtyFlag;
  34639. },
  34640. enumerable: true,
  34641. configurable: true
  34642. });
  34643. Object.defineProperty(Material, "LightDirtyFlag", {
  34644. /**
  34645. * Returns the dirty light flag value
  34646. */
  34647. get: function () {
  34648. return Material._LightDirtyFlag;
  34649. },
  34650. enumerable: true,
  34651. configurable: true
  34652. });
  34653. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34654. /**
  34655. * Returns the dirty fresnel flag value
  34656. */
  34657. get: function () {
  34658. return Material._FresnelDirtyFlag;
  34659. },
  34660. enumerable: true,
  34661. configurable: true
  34662. });
  34663. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34664. /**
  34665. * Returns the dirty attributes flag value
  34666. */
  34667. get: function () {
  34668. return Material._AttributesDirtyFlag;
  34669. },
  34670. enumerable: true,
  34671. configurable: true
  34672. });
  34673. Object.defineProperty(Material, "MiscDirtyFlag", {
  34674. /**
  34675. * Returns the dirty misc flag value
  34676. */
  34677. get: function () {
  34678. return Material._MiscDirtyFlag;
  34679. },
  34680. enumerable: true,
  34681. configurable: true
  34682. });
  34683. Object.defineProperty(Material.prototype, "alpha", {
  34684. /**
  34685. * Gets the alpha value of the material
  34686. */
  34687. get: function () {
  34688. return this._alpha;
  34689. },
  34690. /**
  34691. * Sets the alpha value of the material
  34692. */
  34693. set: function (value) {
  34694. if (this._alpha === value) {
  34695. return;
  34696. }
  34697. this._alpha = value;
  34698. this.markAsDirty(Material.MiscDirtyFlag);
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34704. /**
  34705. * Gets the back-face culling state
  34706. */
  34707. get: function () {
  34708. return this._backFaceCulling;
  34709. },
  34710. /**
  34711. * Sets the back-face culling state
  34712. */
  34713. set: function (value) {
  34714. if (this._backFaceCulling === value) {
  34715. return;
  34716. }
  34717. this._backFaceCulling = value;
  34718. this.markAsDirty(Material.TextureDirtyFlag);
  34719. },
  34720. enumerable: true,
  34721. configurable: true
  34722. });
  34723. Object.defineProperty(Material.prototype, "onDispose", {
  34724. /**
  34725. * Called during a dispose event
  34726. */
  34727. set: function (callback) {
  34728. if (this._onDisposeObserver) {
  34729. this.onDisposeObservable.remove(this._onDisposeObserver);
  34730. }
  34731. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34732. },
  34733. enumerable: true,
  34734. configurable: true
  34735. });
  34736. Object.defineProperty(Material.prototype, "onBind", {
  34737. /**
  34738. * Called during a bind event
  34739. */
  34740. set: function (callback) {
  34741. if (this._onBindObserver) {
  34742. this.onBindObservable.remove(this._onBindObserver);
  34743. }
  34744. this._onBindObserver = this.onBindObservable.add(callback);
  34745. },
  34746. enumerable: true,
  34747. configurable: true
  34748. });
  34749. Object.defineProperty(Material.prototype, "alphaMode", {
  34750. /**
  34751. * Gets the value of the alpha mode
  34752. */
  34753. get: function () {
  34754. return this._alphaMode;
  34755. },
  34756. /**
  34757. * Sets the value of the alpha mode.
  34758. *
  34759. * | Value | Type | Description |
  34760. * | --- | --- | --- |
  34761. * | 0 | ALPHA_DISABLE | |
  34762. * | 1 | ALPHA_ADD | |
  34763. * | 2 | ALPHA_COMBINE | |
  34764. * | 3 | ALPHA_SUBTRACT | |
  34765. * | 4 | ALPHA_MULTIPLY | |
  34766. * | 5 | ALPHA_MAXIMIZED | |
  34767. * | 6 | ALPHA_ONEONE | |
  34768. * | 7 | ALPHA_PREMULTIPLIED | |
  34769. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34770. * | 9 | ALPHA_INTERPOLATE | |
  34771. * | 10 | ALPHA_SCREENMODE | |
  34772. *
  34773. */
  34774. set: function (value) {
  34775. if (this._alphaMode === value) {
  34776. return;
  34777. }
  34778. this._alphaMode = value;
  34779. this.markAsDirty(Material.TextureDirtyFlag);
  34780. },
  34781. enumerable: true,
  34782. configurable: true
  34783. });
  34784. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34785. /**
  34786. * Gets the depth pre-pass value
  34787. */
  34788. get: function () {
  34789. return this._needDepthPrePass;
  34790. },
  34791. /**
  34792. * Sets the need depth pre-pass value
  34793. */
  34794. set: function (value) {
  34795. if (this._needDepthPrePass === value) {
  34796. return;
  34797. }
  34798. this._needDepthPrePass = value;
  34799. if (this._needDepthPrePass) {
  34800. this.checkReadyOnEveryCall = true;
  34801. }
  34802. },
  34803. enumerable: true,
  34804. configurable: true
  34805. });
  34806. Object.defineProperty(Material.prototype, "fogEnabled", {
  34807. /**
  34808. * Gets the value of the fog enabled state
  34809. */
  34810. get: function () {
  34811. return this._fogEnabled;
  34812. },
  34813. /**
  34814. * Sets the state for enabling fog
  34815. */
  34816. set: function (value) {
  34817. if (this._fogEnabled === value) {
  34818. return;
  34819. }
  34820. this._fogEnabled = value;
  34821. this.markAsDirty(Material.MiscDirtyFlag);
  34822. },
  34823. enumerable: true,
  34824. configurable: true
  34825. });
  34826. Object.defineProperty(Material.prototype, "wireframe", {
  34827. /**
  34828. * Gets a value specifying if wireframe mode is enabled
  34829. */
  34830. get: function () {
  34831. switch (this._fillMode) {
  34832. case Material.WireFrameFillMode:
  34833. case Material.LineListDrawMode:
  34834. case Material.LineLoopDrawMode:
  34835. case Material.LineStripDrawMode:
  34836. return true;
  34837. }
  34838. return this._scene.forceWireframe;
  34839. },
  34840. /**
  34841. * Sets the state of wireframe mode
  34842. */
  34843. set: function (value) {
  34844. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34845. },
  34846. enumerable: true,
  34847. configurable: true
  34848. });
  34849. Object.defineProperty(Material.prototype, "pointsCloud", {
  34850. /**
  34851. * Gets the value specifying if point clouds are enabled
  34852. */
  34853. get: function () {
  34854. switch (this._fillMode) {
  34855. case Material.PointFillMode:
  34856. case Material.PointListDrawMode:
  34857. return true;
  34858. }
  34859. return this._scene.forcePointsCloud;
  34860. },
  34861. /**
  34862. * Sets the state of point cloud mode
  34863. */
  34864. set: function (value) {
  34865. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34866. },
  34867. enumerable: true,
  34868. configurable: true
  34869. });
  34870. Object.defineProperty(Material.prototype, "fillMode", {
  34871. /**
  34872. * Gets the material fill mode
  34873. */
  34874. get: function () {
  34875. return this._fillMode;
  34876. },
  34877. /**
  34878. * Sets the material fill mode
  34879. */
  34880. set: function (value) {
  34881. if (this._fillMode === value) {
  34882. return;
  34883. }
  34884. this._fillMode = value;
  34885. this.markAsDirty(Material.MiscDirtyFlag);
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. /**
  34891. * Returns a string representation of the current material
  34892. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34893. * @returns a string with material information
  34894. */
  34895. Material.prototype.toString = function (fullDetails) {
  34896. var ret = "Name: " + this.name;
  34897. if (fullDetails) {
  34898. }
  34899. return ret;
  34900. };
  34901. /**
  34902. * Gets the class name of the material
  34903. * @returns a string with the class name of the material
  34904. */
  34905. Material.prototype.getClassName = function () {
  34906. return "Material";
  34907. };
  34908. Object.defineProperty(Material.prototype, "isFrozen", {
  34909. /**
  34910. * Specifies if updates for the material been locked
  34911. */
  34912. get: function () {
  34913. return this.checkReadyOnlyOnce;
  34914. },
  34915. enumerable: true,
  34916. configurable: true
  34917. });
  34918. /**
  34919. * Locks updates for the material
  34920. */
  34921. Material.prototype.freeze = function () {
  34922. this.checkReadyOnlyOnce = true;
  34923. };
  34924. /**
  34925. * Unlocks updates for the material
  34926. */
  34927. Material.prototype.unfreeze = function () {
  34928. this.checkReadyOnlyOnce = false;
  34929. };
  34930. /**
  34931. * Specifies if the material is ready to be used
  34932. * @param mesh defines the mesh to check
  34933. * @param useInstances specifies if instances should be used
  34934. * @returns a boolean indicating if the material is ready to be used
  34935. */
  34936. Material.prototype.isReady = function (mesh, useInstances) {
  34937. return true;
  34938. };
  34939. /**
  34940. * Specifies that the submesh is ready to be used
  34941. * @param mesh defines the mesh to check
  34942. * @param subMesh defines which submesh to check
  34943. * @param useInstances specifies that instances should be used
  34944. * @returns a boolean indicating that the submesh is ready or not
  34945. */
  34946. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34947. return false;
  34948. };
  34949. /**
  34950. * Returns the material effect
  34951. * @returns the effect associated with the material
  34952. */
  34953. Material.prototype.getEffect = function () {
  34954. return this._effect;
  34955. };
  34956. /**
  34957. * Returns the current scene
  34958. * @returns a Scene
  34959. */
  34960. Material.prototype.getScene = function () {
  34961. return this._scene;
  34962. };
  34963. /**
  34964. * Specifies if the material will require alpha blending
  34965. * @returns a boolean specifying if alpha blending is needed
  34966. */
  34967. Material.prototype.needAlphaBlending = function () {
  34968. return (this.alpha < 1.0);
  34969. };
  34970. /**
  34971. * Specifies if the mesh will require alpha blending
  34972. * @param mesh defines the mesh to check
  34973. * @returns a boolean specifying if alpha blending is needed for the mesh
  34974. */
  34975. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34976. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34977. };
  34978. /**
  34979. * Specifies if this material should be rendered in alpha test mode
  34980. * @returns a boolean specifying if an alpha test is needed.
  34981. */
  34982. Material.prototype.needAlphaTesting = function () {
  34983. return false;
  34984. };
  34985. /**
  34986. * Gets the texture used for the alpha test
  34987. * @returns the texture to use for alpha testing
  34988. */
  34989. Material.prototype.getAlphaTestTexture = function () {
  34990. return null;
  34991. };
  34992. /**
  34993. * Marks the material to indicate that it needs to be re-calculated
  34994. */
  34995. Material.prototype.markDirty = function () {
  34996. this._wasPreviouslyReady = false;
  34997. };
  34998. /** @hidden */
  34999. Material.prototype._preBind = function (effect, overrideOrientation) {
  35000. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35001. var engine = this._scene.getEngine();
  35002. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35003. var reverse = orientation === Material.ClockWiseSideOrientation;
  35004. engine.enableEffect(effect ? effect : this._effect);
  35005. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35006. return reverse;
  35007. };
  35008. /**
  35009. * Binds the material to the mesh
  35010. * @param world defines the world transformation matrix
  35011. * @param mesh defines the mesh to bind the material to
  35012. */
  35013. Material.prototype.bind = function (world, mesh) {
  35014. };
  35015. /**
  35016. * Binds the submesh to the material
  35017. * @param world defines the world transformation matrix
  35018. * @param mesh defines the mesh containing the submesh
  35019. * @param subMesh defines the submesh to bind the material to
  35020. */
  35021. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35022. };
  35023. /**
  35024. * Binds the world matrix to the material
  35025. * @param world defines the world transformation matrix
  35026. */
  35027. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35028. };
  35029. /**
  35030. * Binds the scene's uniform buffer to the effect.
  35031. * @param effect defines the effect to bind to the scene uniform buffer
  35032. * @param sceneUbo defines the uniform buffer storing scene data
  35033. */
  35034. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35035. sceneUbo.bindToEffect(effect, "Scene");
  35036. };
  35037. /**
  35038. * Binds the view matrix to the effect
  35039. * @param effect defines the effect to bind the view matrix to
  35040. */
  35041. Material.prototype.bindView = function (effect) {
  35042. if (!this._useUBO) {
  35043. effect.setMatrix("view", this.getScene().getViewMatrix());
  35044. }
  35045. else {
  35046. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35047. }
  35048. };
  35049. /**
  35050. * Binds the view projection matrix to the effect
  35051. * @param effect defines the effect to bind the view projection matrix to
  35052. */
  35053. Material.prototype.bindViewProjection = function (effect) {
  35054. if (!this._useUBO) {
  35055. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35056. }
  35057. else {
  35058. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35059. }
  35060. };
  35061. /**
  35062. * Specifies if material alpha testing should be turned on for the mesh
  35063. * @param mesh defines the mesh to check
  35064. */
  35065. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35066. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35067. };
  35068. /**
  35069. * Processes to execute after binding the material to a mesh
  35070. * @param mesh defines the rendered mesh
  35071. */
  35072. Material.prototype._afterBind = function (mesh) {
  35073. this._scene._cachedMaterial = this;
  35074. if (mesh) {
  35075. this._scene._cachedVisibility = mesh.visibility;
  35076. }
  35077. else {
  35078. this._scene._cachedVisibility = 1;
  35079. }
  35080. if (mesh) {
  35081. this.onBindObservable.notifyObservers(mesh);
  35082. }
  35083. if (this.disableDepthWrite) {
  35084. var engine = this._scene.getEngine();
  35085. this._cachedDepthWriteState = engine.getDepthWrite();
  35086. engine.setDepthWrite(false);
  35087. }
  35088. };
  35089. /**
  35090. * Unbinds the material from the mesh
  35091. */
  35092. Material.prototype.unbind = function () {
  35093. this.onUnBindObservable.notifyObservers(this);
  35094. if (this.disableDepthWrite) {
  35095. var engine = this._scene.getEngine();
  35096. engine.setDepthWrite(this._cachedDepthWriteState);
  35097. }
  35098. };
  35099. /**
  35100. * Gets the active textures from the material
  35101. * @returns an array of textures
  35102. */
  35103. Material.prototype.getActiveTextures = function () {
  35104. return [];
  35105. };
  35106. /**
  35107. * Specifies if the material uses a texture
  35108. * @param texture defines the texture to check against the material
  35109. * @returns a boolean specifying if the material uses the texture
  35110. */
  35111. Material.prototype.hasTexture = function (texture) {
  35112. return false;
  35113. };
  35114. /**
  35115. * Makes a duplicate of the material, and gives it a new name
  35116. * @param name defines the new name for the duplicated material
  35117. * @returns the cloned material
  35118. */
  35119. Material.prototype.clone = function (name) {
  35120. return null;
  35121. };
  35122. /**
  35123. * Gets the meshes bound to the material
  35124. * @returns an array of meshes bound to the material
  35125. */
  35126. Material.prototype.getBindedMeshes = function () {
  35127. var result = new Array();
  35128. for (var index = 0; index < this._scene.meshes.length; index++) {
  35129. var mesh = this._scene.meshes[index];
  35130. if (mesh.material === this) {
  35131. result.push(mesh);
  35132. }
  35133. }
  35134. return result;
  35135. };
  35136. /**
  35137. * Force shader compilation
  35138. * @param mesh defines the mesh associated with this material
  35139. * @param onCompiled defines a function to execute once the material is compiled
  35140. * @param options defines the options to configure the compilation
  35141. */
  35142. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35143. var _this = this;
  35144. var localOptions = __assign({ clipPlane: false }, options);
  35145. var subMesh = new BABYLON.BaseSubMesh();
  35146. var scene = this.getScene();
  35147. var checkReady = function () {
  35148. if (!_this._scene || !_this._scene.getEngine()) {
  35149. return;
  35150. }
  35151. if (subMesh._materialDefines) {
  35152. subMesh._materialDefines._renderId = -1;
  35153. }
  35154. var clipPlaneState = scene.clipPlane;
  35155. if (localOptions.clipPlane) {
  35156. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35157. }
  35158. if (_this.storeEffectOnSubMeshes) {
  35159. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35160. if (onCompiled) {
  35161. onCompiled(_this);
  35162. }
  35163. }
  35164. else {
  35165. setTimeout(checkReady, 16);
  35166. }
  35167. }
  35168. else {
  35169. if (_this.isReady(mesh)) {
  35170. if (onCompiled) {
  35171. onCompiled(_this);
  35172. }
  35173. }
  35174. else {
  35175. setTimeout(checkReady, 16);
  35176. }
  35177. }
  35178. if (localOptions.clipPlane) {
  35179. scene.clipPlane = clipPlaneState;
  35180. }
  35181. };
  35182. checkReady();
  35183. };
  35184. /**
  35185. * Force shader compilation
  35186. * @param mesh defines the mesh that will use this material
  35187. * @param options defines additional options for compiling the shaders
  35188. * @returns a promise that resolves when the compilation completes
  35189. */
  35190. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35191. var _this = this;
  35192. return new Promise(function (resolve) {
  35193. _this.forceCompilation(mesh, function () {
  35194. resolve();
  35195. }, options);
  35196. });
  35197. };
  35198. /**
  35199. * Marks a define in the material to indicate that it needs to be re-computed
  35200. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35201. */
  35202. Material.prototype.markAsDirty = function (flag) {
  35203. if (flag & Material.TextureDirtyFlag) {
  35204. this._markAllSubMeshesAsTexturesDirty();
  35205. }
  35206. if (flag & Material.LightDirtyFlag) {
  35207. this._markAllSubMeshesAsLightsDirty();
  35208. }
  35209. if (flag & Material.FresnelDirtyFlag) {
  35210. this._markAllSubMeshesAsFresnelDirty();
  35211. }
  35212. if (flag & Material.AttributesDirtyFlag) {
  35213. this._markAllSubMeshesAsAttributesDirty();
  35214. }
  35215. if (flag & Material.MiscDirtyFlag) {
  35216. this._markAllSubMeshesAsMiscDirty();
  35217. }
  35218. this.getScene().resetCachedMaterial();
  35219. };
  35220. /**
  35221. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35222. * @param func defines a function which checks material defines against the submeshes
  35223. */
  35224. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35225. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35226. var mesh = _a[_i];
  35227. if (!mesh.subMeshes) {
  35228. continue;
  35229. }
  35230. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35231. var subMesh = _c[_b];
  35232. if (subMesh.getMaterial() !== this) {
  35233. continue;
  35234. }
  35235. if (!subMesh._materialDefines) {
  35236. continue;
  35237. }
  35238. func(subMesh._materialDefines);
  35239. }
  35240. }
  35241. };
  35242. /**
  35243. * Indicates that image processing needs to be re-calculated for all submeshes
  35244. */
  35245. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35246. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35247. };
  35248. /**
  35249. * Indicates that textures need to be re-calculated for all submeshes
  35250. */
  35251. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35252. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35253. };
  35254. /**
  35255. * Indicates that fresnel needs to be re-calculated for all submeshes
  35256. */
  35257. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35258. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35259. };
  35260. /**
  35261. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35262. */
  35263. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35264. this._markAllSubMeshesAsDirty(function (defines) {
  35265. defines.markAsFresnelDirty();
  35266. defines.markAsMiscDirty();
  35267. });
  35268. };
  35269. /**
  35270. * Indicates that lights need to be re-calculated for all submeshes
  35271. */
  35272. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35273. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35274. };
  35275. /**
  35276. * Indicates that attributes need to be re-calculated for all submeshes
  35277. */
  35278. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35279. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35280. };
  35281. /**
  35282. * Indicates that misc needs to be re-calculated for all submeshes
  35283. */
  35284. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35285. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35286. };
  35287. /**
  35288. * Indicates that textures and misc need to be re-calculated for all submeshes
  35289. */
  35290. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35291. this._markAllSubMeshesAsDirty(function (defines) {
  35292. defines.markAsTexturesDirty();
  35293. defines.markAsMiscDirty();
  35294. });
  35295. };
  35296. /**
  35297. * Disposes the material
  35298. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35299. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35300. */
  35301. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35302. // Animations
  35303. this.getScene().stopAnimation(this);
  35304. this.getScene().freeProcessedMaterials();
  35305. // Remove from scene
  35306. var index = this._scene.materials.indexOf(this);
  35307. if (index >= 0) {
  35308. this._scene.materials.splice(index, 1);
  35309. }
  35310. // Remove from meshes
  35311. for (index = 0; index < this._scene.meshes.length; index++) {
  35312. var mesh = this._scene.meshes[index];
  35313. if (mesh.material === this) {
  35314. mesh.material = null;
  35315. if (mesh.geometry) {
  35316. var geometry = (mesh.geometry);
  35317. if (this.storeEffectOnSubMeshes) {
  35318. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35319. var subMesh = _a[_i];
  35320. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35321. if (forceDisposeEffect && subMesh._materialEffect) {
  35322. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35323. }
  35324. }
  35325. }
  35326. else {
  35327. geometry._releaseVertexArrayObject(this._effect);
  35328. }
  35329. }
  35330. }
  35331. }
  35332. this._uniformBuffer.dispose();
  35333. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35334. if (forceDisposeEffect && this._effect) {
  35335. if (!this.storeEffectOnSubMeshes) {
  35336. this._scene.getEngine()._releaseEffect(this._effect);
  35337. }
  35338. this._effect = null;
  35339. }
  35340. // Callback
  35341. this.onDisposeObservable.notifyObservers(this);
  35342. this.onDisposeObservable.clear();
  35343. this.onBindObservable.clear();
  35344. this.onUnBindObservable.clear();
  35345. };
  35346. /**
  35347. * Serializes this material
  35348. * @returns the serialized material object
  35349. */
  35350. Material.prototype.serialize = function () {
  35351. return BABYLON.SerializationHelper.Serialize(this);
  35352. };
  35353. /**
  35354. * Creates a MultiMaterial from parsed MultiMaterial data.
  35355. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35356. * @param scene defines the hosting scene
  35357. * @returns a new MultiMaterial
  35358. */
  35359. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35360. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35361. multiMaterial.id = parsedMultiMaterial.id;
  35362. if (BABYLON.Tags) {
  35363. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35364. }
  35365. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35366. var subMatId = parsedMultiMaterial.materials[matIndex];
  35367. if (subMatId) {
  35368. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35369. }
  35370. else {
  35371. multiMaterial.subMaterials.push(null);
  35372. }
  35373. }
  35374. return multiMaterial;
  35375. };
  35376. /**
  35377. * Creates a material from parsed material data
  35378. * @param parsedMaterial defines parsed material data
  35379. * @param scene defines the hosting scene
  35380. * @param rootUrl defines the root URL to use to load textures
  35381. * @returns a new material
  35382. */
  35383. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35384. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35385. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35386. }
  35387. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35388. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35389. if (!BABYLON.LegacyPBRMaterial) {
  35390. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35391. return;
  35392. }
  35393. }
  35394. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35395. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35396. };
  35397. // Triangle views
  35398. Material._TriangleFillMode = 0;
  35399. Material._WireFrameFillMode = 1;
  35400. Material._PointFillMode = 2;
  35401. // Draw modes
  35402. Material._PointListDrawMode = 3;
  35403. Material._LineListDrawMode = 4;
  35404. Material._LineLoopDrawMode = 5;
  35405. Material._LineStripDrawMode = 6;
  35406. Material._TriangleStripDrawMode = 7;
  35407. Material._TriangleFanDrawMode = 8;
  35408. /**
  35409. * Stores the clock-wise side orientation
  35410. */
  35411. Material._ClockWiseSideOrientation = 0;
  35412. /**
  35413. * Stores the counter clock-wise side orientation
  35414. */
  35415. Material._CounterClockWiseSideOrientation = 1;
  35416. /**
  35417. * The dirty texture flag value
  35418. */
  35419. Material._TextureDirtyFlag = 1;
  35420. /**
  35421. * The dirty light flag value
  35422. */
  35423. Material._LightDirtyFlag = 2;
  35424. /**
  35425. * The dirty fresnel flag value
  35426. */
  35427. Material._FresnelDirtyFlag = 4;
  35428. /**
  35429. * The dirty attribute flag value
  35430. */
  35431. Material._AttributesDirtyFlag = 8;
  35432. /**
  35433. * The dirty misc flag value
  35434. */
  35435. Material._MiscDirtyFlag = 16;
  35436. __decorate([
  35437. BABYLON.serialize()
  35438. ], Material.prototype, "id", void 0);
  35439. __decorate([
  35440. BABYLON.serialize()
  35441. ], Material.prototype, "uniqueId", void 0);
  35442. __decorate([
  35443. BABYLON.serialize()
  35444. ], Material.prototype, "name", void 0);
  35445. __decorate([
  35446. BABYLON.serialize()
  35447. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35448. __decorate([
  35449. BABYLON.serialize()
  35450. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35451. __decorate([
  35452. BABYLON.serialize()
  35453. ], Material.prototype, "state", void 0);
  35454. __decorate([
  35455. BABYLON.serialize("alpha")
  35456. ], Material.prototype, "_alpha", void 0);
  35457. __decorate([
  35458. BABYLON.serialize("backFaceCulling")
  35459. ], Material.prototype, "_backFaceCulling", void 0);
  35460. __decorate([
  35461. BABYLON.serialize()
  35462. ], Material.prototype, "sideOrientation", void 0);
  35463. __decorate([
  35464. BABYLON.serialize("alphaMode")
  35465. ], Material.prototype, "_alphaMode", void 0);
  35466. __decorate([
  35467. BABYLON.serialize()
  35468. ], Material.prototype, "_needDepthPrePass", void 0);
  35469. __decorate([
  35470. BABYLON.serialize()
  35471. ], Material.prototype, "disableDepthWrite", void 0);
  35472. __decorate([
  35473. BABYLON.serialize()
  35474. ], Material.prototype, "forceDepthWrite", void 0);
  35475. __decorate([
  35476. BABYLON.serialize()
  35477. ], Material.prototype, "separateCullingPass", void 0);
  35478. __decorate([
  35479. BABYLON.serialize("fogEnabled")
  35480. ], Material.prototype, "_fogEnabled", void 0);
  35481. __decorate([
  35482. BABYLON.serialize()
  35483. ], Material.prototype, "pointSize", void 0);
  35484. __decorate([
  35485. BABYLON.serialize()
  35486. ], Material.prototype, "zOffset", void 0);
  35487. __decorate([
  35488. BABYLON.serialize()
  35489. ], Material.prototype, "wireframe", null);
  35490. __decorate([
  35491. BABYLON.serialize()
  35492. ], Material.prototype, "pointsCloud", null);
  35493. __decorate([
  35494. BABYLON.serialize()
  35495. ], Material.prototype, "fillMode", null);
  35496. return Material;
  35497. }());
  35498. BABYLON.Material = Material;
  35499. })(BABYLON || (BABYLON = {}));
  35500. //# sourceMappingURL=babylon.material.js.map
  35501. var BABYLON;
  35502. (function (BABYLON) {
  35503. var UniformBuffer = /** @class */ (function () {
  35504. /**
  35505. * Uniform buffer objects.
  35506. *
  35507. * Handles blocks of uniform on the GPU.
  35508. *
  35509. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35510. *
  35511. * For more information, please refer to :
  35512. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35513. */
  35514. function UniformBuffer(engine, data, dynamic) {
  35515. this._engine = engine;
  35516. this._noUBO = !engine.supportsUniformBuffers;
  35517. this._dynamic = dynamic;
  35518. this._data = data || [];
  35519. this._uniformLocations = {};
  35520. this._uniformSizes = {};
  35521. this._uniformLocationPointer = 0;
  35522. this._needSync = false;
  35523. if (this._noUBO) {
  35524. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35525. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35526. this.updateFloat = this._updateFloatForEffect;
  35527. this.updateFloat2 = this._updateFloat2ForEffect;
  35528. this.updateFloat3 = this._updateFloat3ForEffect;
  35529. this.updateFloat4 = this._updateFloat4ForEffect;
  35530. this.updateMatrix = this._updateMatrixForEffect;
  35531. this.updateVector3 = this._updateVector3ForEffect;
  35532. this.updateVector4 = this._updateVector4ForEffect;
  35533. this.updateColor3 = this._updateColor3ForEffect;
  35534. this.updateColor4 = this._updateColor4ForEffect;
  35535. }
  35536. else {
  35537. this._engine._uniformBuffers.push(this);
  35538. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35539. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35540. this.updateFloat = this._updateFloatForUniform;
  35541. this.updateFloat2 = this._updateFloat2ForUniform;
  35542. this.updateFloat3 = this._updateFloat3ForUniform;
  35543. this.updateFloat4 = this._updateFloat4ForUniform;
  35544. this.updateMatrix = this._updateMatrixForUniform;
  35545. this.updateVector3 = this._updateVector3ForUniform;
  35546. this.updateVector4 = this._updateVector4ForUniform;
  35547. this.updateColor3 = this._updateColor3ForUniform;
  35548. this.updateColor4 = this._updateColor4ForUniform;
  35549. }
  35550. }
  35551. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35552. // Properties
  35553. /**
  35554. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35555. * or just falling back on setUniformXXX calls.
  35556. */
  35557. get: function () {
  35558. return !this._noUBO;
  35559. },
  35560. enumerable: true,
  35561. configurable: true
  35562. });
  35563. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35564. /**
  35565. * Indicates if the WebGL underlying uniform buffer is in sync
  35566. * with the javascript cache data.
  35567. */
  35568. get: function () {
  35569. return !this._needSync;
  35570. },
  35571. enumerable: true,
  35572. configurable: true
  35573. });
  35574. /**
  35575. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35576. * Also, a dynamic UniformBuffer will disable cache verification and always
  35577. * update the underlying WebGL uniform buffer to the GPU.
  35578. */
  35579. UniformBuffer.prototype.isDynamic = function () {
  35580. return this._dynamic !== undefined;
  35581. };
  35582. /**
  35583. * The data cache on JS side.
  35584. */
  35585. UniformBuffer.prototype.getData = function () {
  35586. return this._bufferData;
  35587. };
  35588. /**
  35589. * The underlying WebGL Uniform buffer.
  35590. */
  35591. UniformBuffer.prototype.getBuffer = function () {
  35592. return this._buffer;
  35593. };
  35594. /**
  35595. * std140 layout specifies how to align data within an UBO structure.
  35596. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35597. * for specs.
  35598. */
  35599. UniformBuffer.prototype._fillAlignment = function (size) {
  35600. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35601. // and 4x4 matrices
  35602. // TODO : change if other types are used
  35603. var alignment;
  35604. if (size <= 2) {
  35605. alignment = size;
  35606. }
  35607. else {
  35608. alignment = 4;
  35609. }
  35610. if ((this._uniformLocationPointer % alignment) !== 0) {
  35611. var oldPointer = this._uniformLocationPointer;
  35612. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35613. var diff = this._uniformLocationPointer - oldPointer;
  35614. for (var i = 0; i < diff; i++) {
  35615. this._data.push(0);
  35616. }
  35617. }
  35618. };
  35619. /**
  35620. * Adds an uniform in the buffer.
  35621. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35622. * for the layout to be correct !
  35623. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35624. * @param {number|number[]} size Data size, or data directly.
  35625. */
  35626. UniformBuffer.prototype.addUniform = function (name, size) {
  35627. if (this._noUBO) {
  35628. return;
  35629. }
  35630. if (this._uniformLocations[name] !== undefined) {
  35631. // Already existing uniform
  35632. return;
  35633. }
  35634. // This function must be called in the order of the shader layout !
  35635. // size can be the size of the uniform, or data directly
  35636. var data;
  35637. if (size instanceof Array) {
  35638. data = size;
  35639. size = data.length;
  35640. }
  35641. else {
  35642. size = size;
  35643. data = [];
  35644. // Fill with zeros
  35645. for (var i = 0; i < size; i++) {
  35646. data.push(0);
  35647. }
  35648. }
  35649. this._fillAlignment(size);
  35650. this._uniformSizes[name] = size;
  35651. this._uniformLocations[name] = this._uniformLocationPointer;
  35652. this._uniformLocationPointer += size;
  35653. for (var i = 0; i < size; i++) {
  35654. this._data.push(data[i]);
  35655. }
  35656. this._needSync = true;
  35657. };
  35658. /**
  35659. * Wrapper for addUniform.
  35660. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35661. * @param {Matrix} mat A 4x4 matrix.
  35662. */
  35663. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35664. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35665. };
  35666. /**
  35667. * Wrapper for addUniform.
  35668. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35669. * @param {number} x
  35670. * @param {number} y
  35671. */
  35672. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35673. var temp = [x, y];
  35674. this.addUniform(name, temp);
  35675. };
  35676. /**
  35677. * Wrapper for addUniform.
  35678. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35679. * @param {number} x
  35680. * @param {number} y
  35681. * @param {number} z
  35682. */
  35683. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35684. var temp = [x, y, z];
  35685. this.addUniform(name, temp);
  35686. };
  35687. /**
  35688. * Wrapper for addUniform.
  35689. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35690. * @param {Color3} color
  35691. */
  35692. UniformBuffer.prototype.addColor3 = function (name, color) {
  35693. var temp = new Array();
  35694. color.toArray(temp);
  35695. this.addUniform(name, temp);
  35696. };
  35697. /**
  35698. * Wrapper for addUniform.
  35699. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35700. * @param {Color3} color
  35701. * @param {number} alpha
  35702. */
  35703. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35704. var temp = new Array();
  35705. color.toArray(temp);
  35706. temp.push(alpha);
  35707. this.addUniform(name, temp);
  35708. };
  35709. /**
  35710. * Wrapper for addUniform.
  35711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35712. * @param {Vector3} vector
  35713. */
  35714. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35715. var temp = new Array();
  35716. vector.toArray(temp);
  35717. this.addUniform(name, temp);
  35718. };
  35719. /**
  35720. * Wrapper for addUniform.
  35721. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35722. */
  35723. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35724. this.addUniform(name, 12);
  35725. };
  35726. /**
  35727. * Wrapper for addUniform.
  35728. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35729. */
  35730. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35731. this.addUniform(name, 8);
  35732. };
  35733. /**
  35734. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35735. */
  35736. UniformBuffer.prototype.create = function () {
  35737. if (this._noUBO) {
  35738. return;
  35739. }
  35740. if (this._buffer) {
  35741. return; // nothing to do
  35742. }
  35743. // See spec, alignment must be filled as a vec4
  35744. this._fillAlignment(4);
  35745. this._bufferData = new Float32Array(this._data);
  35746. this._rebuild();
  35747. this._needSync = true;
  35748. };
  35749. UniformBuffer.prototype._rebuild = function () {
  35750. if (this._noUBO) {
  35751. return;
  35752. }
  35753. if (this._dynamic) {
  35754. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35755. }
  35756. else {
  35757. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35758. }
  35759. };
  35760. /**
  35761. * Updates the WebGL Uniform Buffer on the GPU.
  35762. * If the `dynamic` flag is set to true, no cache comparison is done.
  35763. * Otherwise, the buffer will be updated only if the cache differs.
  35764. */
  35765. UniformBuffer.prototype.update = function () {
  35766. if (!this._buffer) {
  35767. this.create();
  35768. return;
  35769. }
  35770. if (!this._dynamic && !this._needSync) {
  35771. return;
  35772. }
  35773. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35774. this._needSync = false;
  35775. };
  35776. /**
  35777. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35778. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35779. * @param {number[]|Float32Array} data Flattened data
  35780. * @param {number} size Size of the data.
  35781. */
  35782. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35783. var location = this._uniformLocations[uniformName];
  35784. if (location === undefined) {
  35785. if (this._buffer) {
  35786. // Cannot add an uniform if the buffer is already created
  35787. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35788. return;
  35789. }
  35790. this.addUniform(uniformName, size);
  35791. location = this._uniformLocations[uniformName];
  35792. }
  35793. if (!this._buffer) {
  35794. this.create();
  35795. }
  35796. if (!this._dynamic) {
  35797. // Cache for static uniform buffers
  35798. var changed = false;
  35799. for (var i = 0; i < size; i++) {
  35800. if (this._bufferData[location + i] !== data[i]) {
  35801. changed = true;
  35802. this._bufferData[location + i] = data[i];
  35803. }
  35804. }
  35805. this._needSync = this._needSync || changed;
  35806. }
  35807. else {
  35808. // No cache for dynamic
  35809. for (var i = 0; i < size; i++) {
  35810. this._bufferData[location + i] = data[i];
  35811. }
  35812. }
  35813. };
  35814. // Update methods
  35815. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35816. // To match std140, matrix must be realigned
  35817. for (var i = 0; i < 3; i++) {
  35818. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35819. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35820. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35821. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35822. }
  35823. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35824. };
  35825. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35826. this._currentEffect.setMatrix3x3(name, matrix);
  35827. };
  35828. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35829. this._currentEffect.setMatrix2x2(name, matrix);
  35830. };
  35831. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35832. // To match std140, matrix must be realigned
  35833. for (var i = 0; i < 2; i++) {
  35834. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35835. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35836. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35837. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35838. }
  35839. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35840. };
  35841. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35842. this._currentEffect.setFloat(name, x);
  35843. };
  35844. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35845. UniformBuffer._tempBuffer[0] = x;
  35846. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35847. };
  35848. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35849. if (suffix === void 0) { suffix = ""; }
  35850. this._currentEffect.setFloat2(name + suffix, x, y);
  35851. };
  35852. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35853. if (suffix === void 0) { suffix = ""; }
  35854. UniformBuffer._tempBuffer[0] = x;
  35855. UniformBuffer._tempBuffer[1] = y;
  35856. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35857. };
  35858. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35859. if (suffix === void 0) { suffix = ""; }
  35860. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35861. };
  35862. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35863. if (suffix === void 0) { suffix = ""; }
  35864. UniformBuffer._tempBuffer[0] = x;
  35865. UniformBuffer._tempBuffer[1] = y;
  35866. UniformBuffer._tempBuffer[2] = z;
  35867. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35868. };
  35869. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35870. if (suffix === void 0) { suffix = ""; }
  35871. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35872. };
  35873. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35874. if (suffix === void 0) { suffix = ""; }
  35875. UniformBuffer._tempBuffer[0] = x;
  35876. UniformBuffer._tempBuffer[1] = y;
  35877. UniformBuffer._tempBuffer[2] = z;
  35878. UniformBuffer._tempBuffer[3] = w;
  35879. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35880. };
  35881. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35882. this._currentEffect.setMatrix(name, mat);
  35883. };
  35884. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35885. this.updateUniform(name, mat.toArray(), 16);
  35886. };
  35887. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35888. this._currentEffect.setVector3(name, vector);
  35889. };
  35890. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35891. vector.toArray(UniformBuffer._tempBuffer);
  35892. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35893. };
  35894. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35895. this._currentEffect.setVector4(name, vector);
  35896. };
  35897. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35898. vector.toArray(UniformBuffer._tempBuffer);
  35899. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35900. };
  35901. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35902. if (suffix === void 0) { suffix = ""; }
  35903. this._currentEffect.setColor3(name + suffix, color);
  35904. };
  35905. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35906. if (suffix === void 0) { suffix = ""; }
  35907. color.toArray(UniformBuffer._tempBuffer);
  35908. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35909. };
  35910. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35911. if (suffix === void 0) { suffix = ""; }
  35912. this._currentEffect.setColor4(name + suffix, color, alpha);
  35913. };
  35914. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35915. if (suffix === void 0) { suffix = ""; }
  35916. color.toArray(UniformBuffer._tempBuffer);
  35917. UniformBuffer._tempBuffer[3] = alpha;
  35918. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35919. };
  35920. /**
  35921. * Sets a sampler uniform on the effect.
  35922. * @param {string} name Name of the sampler.
  35923. * @param {Texture} texture
  35924. */
  35925. UniformBuffer.prototype.setTexture = function (name, texture) {
  35926. this._currentEffect.setTexture(name, texture);
  35927. };
  35928. /**
  35929. * Directly updates the value of the uniform in the cache AND on the GPU.
  35930. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35931. * @param {number[]|Float32Array} data Flattened data
  35932. */
  35933. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35934. this.updateUniform(uniformName, data, data.length);
  35935. this.update();
  35936. };
  35937. /**
  35938. * Binds this uniform buffer to an effect.
  35939. * @param {Effect} effect
  35940. * @param {string} name Name of the uniform block in the shader.
  35941. */
  35942. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35943. this._currentEffect = effect;
  35944. if (this._noUBO || !this._buffer) {
  35945. return;
  35946. }
  35947. effect.bindUniformBuffer(this._buffer, name);
  35948. };
  35949. /**
  35950. * Disposes the uniform buffer.
  35951. */
  35952. UniformBuffer.prototype.dispose = function () {
  35953. if (this._noUBO) {
  35954. return;
  35955. }
  35956. var index = this._engine._uniformBuffers.indexOf(this);
  35957. if (index !== -1) {
  35958. this._engine._uniformBuffers.splice(index, 1);
  35959. }
  35960. if (!this._buffer) {
  35961. return;
  35962. }
  35963. if (this._engine._releaseBuffer(this._buffer)) {
  35964. this._buffer = null;
  35965. }
  35966. };
  35967. // Pool for avoiding memory leaks
  35968. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35969. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35970. return UniformBuffer;
  35971. }());
  35972. BABYLON.UniformBuffer = UniformBuffer;
  35973. })(BABYLON || (BABYLON = {}));
  35974. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35975. var BABYLON;
  35976. (function (BABYLON) {
  35977. /**
  35978. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35979. */
  35980. var VertexData = /** @class */ (function () {
  35981. function VertexData() {
  35982. }
  35983. /**
  35984. * Uses the passed data array to set the set the values for the specified kind of data
  35985. * @param data a linear array of floating numbers
  35986. * @param kind the type of data that is being set, eg positions, colors etc
  35987. */
  35988. VertexData.prototype.set = function (data, kind) {
  35989. switch (kind) {
  35990. case BABYLON.VertexBuffer.PositionKind:
  35991. this.positions = data;
  35992. break;
  35993. case BABYLON.VertexBuffer.NormalKind:
  35994. this.normals = data;
  35995. break;
  35996. case BABYLON.VertexBuffer.TangentKind:
  35997. this.tangents = data;
  35998. break;
  35999. case BABYLON.VertexBuffer.UVKind:
  36000. this.uvs = data;
  36001. break;
  36002. case BABYLON.VertexBuffer.UV2Kind:
  36003. this.uvs2 = data;
  36004. break;
  36005. case BABYLON.VertexBuffer.UV3Kind:
  36006. this.uvs3 = data;
  36007. break;
  36008. case BABYLON.VertexBuffer.UV4Kind:
  36009. this.uvs4 = data;
  36010. break;
  36011. case BABYLON.VertexBuffer.UV5Kind:
  36012. this.uvs5 = data;
  36013. break;
  36014. case BABYLON.VertexBuffer.UV6Kind:
  36015. this.uvs6 = data;
  36016. break;
  36017. case BABYLON.VertexBuffer.ColorKind:
  36018. this.colors = data;
  36019. break;
  36020. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36021. this.matricesIndices = data;
  36022. break;
  36023. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36024. this.matricesWeights = data;
  36025. break;
  36026. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36027. this.matricesIndicesExtra = data;
  36028. break;
  36029. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36030. this.matricesWeightsExtra = data;
  36031. break;
  36032. }
  36033. };
  36034. /**
  36035. * Associates the vertexData to the passed Mesh.
  36036. * Sets it as updatable or not (default `false`)
  36037. * @param mesh the mesh the vertexData is applied to
  36038. * @param updatable when used and having the value true allows new data to update the vertexData
  36039. * @returns the VertexData
  36040. */
  36041. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36042. this._applyTo(mesh, updatable);
  36043. return this;
  36044. };
  36045. /**
  36046. * Associates the vertexData to the passed Geometry.
  36047. * Sets it as updatable or not (default `false`)
  36048. * @param geometry the geometry the vertexData is applied to
  36049. * @param updatable when used and having the value true allows new data to update the vertexData
  36050. * @returns VertexData
  36051. */
  36052. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36053. this._applyTo(geometry, updatable);
  36054. return this;
  36055. };
  36056. /**
  36057. * Updates the associated mesh
  36058. * @param mesh the mesh to be updated
  36059. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36060. * @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
  36061. * @returns VertexData
  36062. */
  36063. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36064. this._update(mesh);
  36065. return this;
  36066. };
  36067. /**
  36068. * Updates the associated geometry
  36069. * @param geometry the geometry to be updated
  36070. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36071. * @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
  36072. * @returns VertexData.
  36073. */
  36074. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36075. this._update(geometry);
  36076. return this;
  36077. };
  36078. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36079. if (updatable === void 0) { updatable = false; }
  36080. if (this.positions) {
  36081. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36082. }
  36083. if (this.normals) {
  36084. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36085. }
  36086. if (this.tangents) {
  36087. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36088. }
  36089. if (this.uvs) {
  36090. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36091. }
  36092. if (this.uvs2) {
  36093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36094. }
  36095. if (this.uvs3) {
  36096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36097. }
  36098. if (this.uvs4) {
  36099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36100. }
  36101. if (this.uvs5) {
  36102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36103. }
  36104. if (this.uvs6) {
  36105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36106. }
  36107. if (this.colors) {
  36108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36109. }
  36110. if (this.matricesIndices) {
  36111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36112. }
  36113. if (this.matricesWeights) {
  36114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36115. }
  36116. if (this.matricesIndicesExtra) {
  36117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36118. }
  36119. if (this.matricesWeightsExtra) {
  36120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36121. }
  36122. if (this.indices) {
  36123. meshOrGeometry.setIndices(this.indices, null, updatable);
  36124. }
  36125. else {
  36126. meshOrGeometry.setIndices([], null);
  36127. }
  36128. return this;
  36129. };
  36130. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36131. if (this.positions) {
  36132. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36133. }
  36134. if (this.normals) {
  36135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36136. }
  36137. if (this.tangents) {
  36138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36139. }
  36140. if (this.uvs) {
  36141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36142. }
  36143. if (this.uvs2) {
  36144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36145. }
  36146. if (this.uvs3) {
  36147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36148. }
  36149. if (this.uvs4) {
  36150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36151. }
  36152. if (this.uvs5) {
  36153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36154. }
  36155. if (this.uvs6) {
  36156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36157. }
  36158. if (this.colors) {
  36159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36160. }
  36161. if (this.matricesIndices) {
  36162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36163. }
  36164. if (this.matricesWeights) {
  36165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36166. }
  36167. if (this.matricesIndicesExtra) {
  36168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36169. }
  36170. if (this.matricesWeightsExtra) {
  36171. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36172. }
  36173. if (this.indices) {
  36174. meshOrGeometry.setIndices(this.indices, null);
  36175. }
  36176. return this;
  36177. };
  36178. /**
  36179. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36180. * @param matrix the transforming matrix
  36181. * @returns the VertexData
  36182. */
  36183. VertexData.prototype.transform = function (matrix) {
  36184. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36185. var transformed = BABYLON.Vector3.Zero();
  36186. var index;
  36187. if (this.positions) {
  36188. var position = BABYLON.Vector3.Zero();
  36189. for (index = 0; index < this.positions.length; index += 3) {
  36190. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36191. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36192. this.positions[index] = transformed.x;
  36193. this.positions[index + 1] = transformed.y;
  36194. this.positions[index + 2] = transformed.z;
  36195. }
  36196. }
  36197. if (this.normals) {
  36198. var normal = BABYLON.Vector3.Zero();
  36199. for (index = 0; index < this.normals.length; index += 3) {
  36200. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36201. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36202. this.normals[index] = transformed.x;
  36203. this.normals[index + 1] = transformed.y;
  36204. this.normals[index + 2] = transformed.z;
  36205. }
  36206. }
  36207. if (this.tangents) {
  36208. var tangent = BABYLON.Vector4.Zero();
  36209. var tangentTransformed = BABYLON.Vector4.Zero();
  36210. for (index = 0; index < this.tangents.length; index += 4) {
  36211. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36212. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36213. this.tangents[index] = tangentTransformed.x;
  36214. this.tangents[index + 1] = tangentTransformed.y;
  36215. this.tangents[index + 2] = tangentTransformed.z;
  36216. this.tangents[index + 3] = tangentTransformed.w;
  36217. }
  36218. }
  36219. if (flip && this.indices) {
  36220. for (index = 0; index < this.indices.length; index += 3) {
  36221. var tmp = this.indices[index + 1];
  36222. this.indices[index + 1] = this.indices[index + 2];
  36223. this.indices[index + 2] = tmp;
  36224. }
  36225. }
  36226. return this;
  36227. };
  36228. /**
  36229. * Merges the passed VertexData into the current one
  36230. * @param other the VertexData to be merged into the current one
  36231. * @returns the modified VertexData
  36232. */
  36233. VertexData.prototype.merge = function (other) {
  36234. this._validate();
  36235. other._validate();
  36236. if (!this.normals !== !other.normals ||
  36237. !this.tangents !== !other.tangents ||
  36238. !this.uvs !== !other.uvs ||
  36239. !this.uvs2 !== !other.uvs2 ||
  36240. !this.uvs3 !== !other.uvs3 ||
  36241. !this.uvs4 !== !other.uvs4 ||
  36242. !this.uvs5 !== !other.uvs5 ||
  36243. !this.uvs6 !== !other.uvs6 ||
  36244. !this.colors !== !other.colors ||
  36245. !this.matricesIndices !== !other.matricesIndices ||
  36246. !this.matricesWeights !== !other.matricesWeights ||
  36247. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36248. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36249. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36250. }
  36251. if (other.indices) {
  36252. if (!this.indices) {
  36253. this.indices = [];
  36254. }
  36255. var offset = this.positions ? this.positions.length / 3 : 0;
  36256. for (var index = 0; index < other.indices.length; index++) {
  36257. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36258. this.indices.push(other.indices[index] + offset);
  36259. }
  36260. }
  36261. this.positions = this._mergeElement(this.positions, other.positions);
  36262. this.normals = this._mergeElement(this.normals, other.normals);
  36263. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36264. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36265. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36266. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36267. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36268. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36269. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36270. this.colors = this._mergeElement(this.colors, other.colors);
  36271. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36272. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36273. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36274. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36275. return this;
  36276. };
  36277. VertexData.prototype._mergeElement = function (source, other) {
  36278. if (!source) {
  36279. return other;
  36280. }
  36281. if (!other) {
  36282. return source;
  36283. }
  36284. var len = other.length + source.length;
  36285. var isSrcTypedArray = source instanceof Float32Array;
  36286. var isOthTypedArray = other instanceof Float32Array;
  36287. // use non-loop method when the source is Float32Array
  36288. if (isSrcTypedArray) {
  36289. var ret32 = new Float32Array(len);
  36290. ret32.set(source);
  36291. ret32.set(other, source.length);
  36292. return ret32;
  36293. // source is number[], when other is also use concat
  36294. }
  36295. else if (!isOthTypedArray) {
  36296. return source.concat(other);
  36297. // source is a number[], but other is a Float32Array, loop required
  36298. }
  36299. else {
  36300. var ret = source.slice(0); // copy source to a separate array
  36301. for (var i = 0, len = other.length; i < len; i++) {
  36302. ret.push(other[i]);
  36303. }
  36304. return ret;
  36305. }
  36306. };
  36307. VertexData.prototype._validate = function () {
  36308. if (!this.positions) {
  36309. throw new Error("Positions are required");
  36310. }
  36311. var getElementCount = function (kind, values) {
  36312. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36313. if ((values.length % stride) !== 0) {
  36314. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36315. }
  36316. return values.length / stride;
  36317. };
  36318. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36319. var validateElementCount = function (kind, values) {
  36320. var elementCount = getElementCount(kind, values);
  36321. if (elementCount !== positionsElementCount) {
  36322. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36323. }
  36324. };
  36325. if (this.normals)
  36326. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36327. if (this.tangents)
  36328. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36329. if (this.uvs)
  36330. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36331. if (this.uvs2)
  36332. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36333. if (this.uvs3)
  36334. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36335. if (this.uvs4)
  36336. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36337. if (this.uvs5)
  36338. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36339. if (this.uvs6)
  36340. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36341. if (this.colors)
  36342. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36343. if (this.matricesIndices)
  36344. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36345. if (this.matricesWeights)
  36346. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36347. if (this.matricesIndicesExtra)
  36348. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36349. if (this.matricesWeightsExtra)
  36350. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36351. };
  36352. /**
  36353. * Serializes the VertexData
  36354. * @returns a serialized object
  36355. */
  36356. VertexData.prototype.serialize = function () {
  36357. var serializationObject = this.serialize();
  36358. if (this.positions) {
  36359. serializationObject.positions = this.positions;
  36360. }
  36361. if (this.normals) {
  36362. serializationObject.normals = this.normals;
  36363. }
  36364. if (this.tangents) {
  36365. serializationObject.tangents = this.tangents;
  36366. }
  36367. if (this.uvs) {
  36368. serializationObject.uvs = this.uvs;
  36369. }
  36370. if (this.uvs2) {
  36371. serializationObject.uvs2 = this.uvs2;
  36372. }
  36373. if (this.uvs3) {
  36374. serializationObject.uvs3 = this.uvs3;
  36375. }
  36376. if (this.uvs4) {
  36377. serializationObject.uvs4 = this.uvs4;
  36378. }
  36379. if (this.uvs5) {
  36380. serializationObject.uvs5 = this.uvs5;
  36381. }
  36382. if (this.uvs6) {
  36383. serializationObject.uvs6 = this.uvs6;
  36384. }
  36385. if (this.colors) {
  36386. serializationObject.colors = this.colors;
  36387. }
  36388. if (this.matricesIndices) {
  36389. serializationObject.matricesIndices = this.matricesIndices;
  36390. serializationObject.matricesIndices._isExpanded = true;
  36391. }
  36392. if (this.matricesWeights) {
  36393. serializationObject.matricesWeights = this.matricesWeights;
  36394. }
  36395. if (this.matricesIndicesExtra) {
  36396. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36397. serializationObject.matricesIndicesExtra._isExpanded = true;
  36398. }
  36399. if (this.matricesWeightsExtra) {
  36400. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36401. }
  36402. serializationObject.indices = this.indices;
  36403. return serializationObject;
  36404. };
  36405. // Statics
  36406. /**
  36407. * Extracts the vertexData from a mesh
  36408. * @param mesh the mesh from which to extract the VertexData
  36409. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36410. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36411. * @returns the object VertexData associated to the passed mesh
  36412. */
  36413. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36414. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36415. };
  36416. /**
  36417. * Extracts the vertexData from the geometry
  36418. * @param geometry the geometry from which to extract the VertexData
  36419. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36420. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36421. * @returns the object VertexData associated to the passed mesh
  36422. */
  36423. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36424. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36425. };
  36426. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36427. var result = new VertexData();
  36428. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36429. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36430. }
  36431. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36432. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36433. }
  36434. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36435. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36436. }
  36437. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36438. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36439. }
  36440. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36441. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36442. }
  36443. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36444. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36445. }
  36446. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36447. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36448. }
  36449. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36450. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36451. }
  36452. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36453. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36454. }
  36455. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36456. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36457. }
  36458. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36459. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36460. }
  36461. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36462. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36463. }
  36464. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36465. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36466. }
  36467. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36468. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36469. }
  36470. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36471. return result;
  36472. };
  36473. /**
  36474. * Creates the VertexData for a Ribbon
  36475. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36476. * * pathArray array of paths, each of which an array of successive Vector3
  36477. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36478. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36479. * * 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
  36480. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36481. * * 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)
  36482. * * 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)
  36483. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36484. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36485. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36486. * @returns the VertexData of the ribbon
  36487. */
  36488. VertexData.CreateRibbon = function (options) {
  36489. var pathArray = options.pathArray;
  36490. var closeArray = options.closeArray || false;
  36491. var closePath = options.closePath || false;
  36492. var invertUV = options.invertUV || false;
  36493. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36494. var offset = options.offset || defaultOffset;
  36495. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36496. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36497. var customUV = options.uvs;
  36498. var customColors = options.colors;
  36499. var positions = [];
  36500. var indices = [];
  36501. var normals = [];
  36502. var uvs = [];
  36503. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36504. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36505. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36506. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36507. var minlg; // minimal length among all paths from pathArray
  36508. var lg = []; // array of path lengths : nb of vertex per path
  36509. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36510. var p; // path iterator
  36511. var i; // point iterator
  36512. var j; // point iterator
  36513. // if single path in pathArray
  36514. if (pathArray.length < 2) {
  36515. var ar1 = [];
  36516. var ar2 = [];
  36517. for (i = 0; i < pathArray[0].length - offset; i++) {
  36518. ar1.push(pathArray[0][i]);
  36519. ar2.push(pathArray[0][i + offset]);
  36520. }
  36521. pathArray = [ar1, ar2];
  36522. }
  36523. // positions and horizontal distances (u)
  36524. var idc = 0;
  36525. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36526. var path;
  36527. var l;
  36528. minlg = pathArray[0].length;
  36529. var vectlg;
  36530. var dist;
  36531. for (p = 0; p < pathArray.length; p++) {
  36532. uTotalDistance[p] = 0;
  36533. us[p] = [0];
  36534. path = pathArray[p];
  36535. l = path.length;
  36536. minlg = (minlg < l) ? minlg : l;
  36537. j = 0;
  36538. while (j < l) {
  36539. positions.push(path[j].x, path[j].y, path[j].z);
  36540. if (j > 0) {
  36541. vectlg = path[j].subtract(path[j - 1]).length();
  36542. dist = vectlg + uTotalDistance[p];
  36543. us[p].push(dist);
  36544. uTotalDistance[p] = dist;
  36545. }
  36546. j++;
  36547. }
  36548. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36549. j--;
  36550. positions.push(path[0].x, path[0].y, path[0].z);
  36551. vectlg = path[j].subtract(path[0]).length();
  36552. dist = vectlg + uTotalDistance[p];
  36553. us[p].push(dist);
  36554. uTotalDistance[p] = dist;
  36555. }
  36556. lg[p] = l + closePathCorr;
  36557. idx[p] = idc;
  36558. idc += (l + closePathCorr);
  36559. }
  36560. // vertical distances (v)
  36561. var path1;
  36562. var path2;
  36563. var vertex1 = null;
  36564. var vertex2 = null;
  36565. for (i = 0; i < minlg + closePathCorr; i++) {
  36566. vTotalDistance[i] = 0;
  36567. vs[i] = [0];
  36568. for (p = 0; p < pathArray.length - 1; p++) {
  36569. path1 = pathArray[p];
  36570. path2 = pathArray[p + 1];
  36571. if (i === minlg) { // closePath
  36572. vertex1 = path1[0];
  36573. vertex2 = path2[0];
  36574. }
  36575. else {
  36576. vertex1 = path1[i];
  36577. vertex2 = path2[i];
  36578. }
  36579. vectlg = vertex2.subtract(vertex1).length();
  36580. dist = vectlg + vTotalDistance[i];
  36581. vs[i].push(dist);
  36582. vTotalDistance[i] = dist;
  36583. }
  36584. if (closeArray && vertex2 && vertex1) {
  36585. path1 = pathArray[p];
  36586. path2 = pathArray[0];
  36587. if (i === minlg) { // closePath
  36588. vertex2 = path2[0];
  36589. }
  36590. vectlg = vertex2.subtract(vertex1).length();
  36591. dist = vectlg + vTotalDistance[i];
  36592. vTotalDistance[i] = dist;
  36593. }
  36594. }
  36595. // uvs
  36596. var u;
  36597. var v;
  36598. if (customUV) {
  36599. for (p = 0; p < customUV.length; p++) {
  36600. uvs.push(customUV[p].x, customUV[p].y);
  36601. }
  36602. }
  36603. else {
  36604. for (p = 0; p < pathArray.length; p++) {
  36605. for (i = 0; i < minlg + closePathCorr; i++) {
  36606. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36607. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36608. if (invertUV) {
  36609. uvs.push(v, u);
  36610. }
  36611. else {
  36612. uvs.push(u, v);
  36613. }
  36614. }
  36615. }
  36616. }
  36617. // indices
  36618. p = 0; // path index
  36619. var pi = 0; // positions array index
  36620. var l1 = lg[p] - 1; // path1 length
  36621. var l2 = lg[p + 1] - 1; // path2 length
  36622. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36623. var shft = idx[1] - idx[0]; // shift
  36624. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36625. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36626. // 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
  36627. indices.push(pi, pi + shft, pi + 1);
  36628. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36629. pi += 1;
  36630. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36631. p++;
  36632. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36633. shft = idx[0] - idx[p];
  36634. l1 = lg[p] - 1;
  36635. l2 = lg[0] - 1;
  36636. }
  36637. else {
  36638. shft = idx[p + 1] - idx[p];
  36639. l1 = lg[p] - 1;
  36640. l2 = lg[p + 1] - 1;
  36641. }
  36642. pi = idx[p];
  36643. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36644. }
  36645. }
  36646. // normals
  36647. VertexData.ComputeNormals(positions, indices, normals);
  36648. if (closePath) { // update both the first and last vertex normals to their average value
  36649. var indexFirst = 0;
  36650. var indexLast = 0;
  36651. for (p = 0; p < pathArray.length; p++) {
  36652. indexFirst = idx[p] * 3;
  36653. if (p + 1 < pathArray.length) {
  36654. indexLast = (idx[p + 1] - 1) * 3;
  36655. }
  36656. else {
  36657. indexLast = normals.length - 3;
  36658. }
  36659. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36660. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36661. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36662. normals[indexLast] = normals[indexFirst];
  36663. normals[indexLast + 1] = normals[indexFirst + 1];
  36664. normals[indexLast + 2] = normals[indexFirst + 2];
  36665. }
  36666. }
  36667. // sides
  36668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36669. // Colors
  36670. var colors = null;
  36671. if (customColors) {
  36672. colors = new Float32Array(customColors.length * 4);
  36673. for (var c = 0; c < customColors.length; c++) {
  36674. colors[c * 4] = customColors[c].r;
  36675. colors[c * 4 + 1] = customColors[c].g;
  36676. colors[c * 4 + 2] = customColors[c].b;
  36677. colors[c * 4 + 3] = customColors[c].a;
  36678. }
  36679. }
  36680. // Result
  36681. var vertexData = new VertexData();
  36682. var positions32 = new Float32Array(positions);
  36683. var normals32 = new Float32Array(normals);
  36684. var uvs32 = new Float32Array(uvs);
  36685. vertexData.indices = indices;
  36686. vertexData.positions = positions32;
  36687. vertexData.normals = normals32;
  36688. vertexData.uvs = uvs32;
  36689. if (colors) {
  36690. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36691. }
  36692. if (closePath) {
  36693. vertexData._idx = idx;
  36694. }
  36695. return vertexData;
  36696. };
  36697. /**
  36698. * Creates the VertexData for a box
  36699. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36700. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36701. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36702. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36703. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36704. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36705. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36706. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36707. * * 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)
  36708. * * 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)
  36709. * @returns the VertexData of the box
  36710. */
  36711. VertexData.CreateBox = function (options) {
  36712. var normalsSource = [
  36713. new BABYLON.Vector3(0, 0, 1),
  36714. new BABYLON.Vector3(0, 0, -1),
  36715. new BABYLON.Vector3(1, 0, 0),
  36716. new BABYLON.Vector3(-1, 0, 0),
  36717. new BABYLON.Vector3(0, 1, 0),
  36718. new BABYLON.Vector3(0, -1, 0)
  36719. ];
  36720. var indices = [];
  36721. var positions = [];
  36722. var normals = [];
  36723. var uvs = [];
  36724. var width = options.width || options.size || 1;
  36725. var height = options.height || options.size || 1;
  36726. var depth = options.depth || options.size || 1;
  36727. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36728. var faceUV = options.faceUV || new Array(6);
  36729. var faceColors = options.faceColors;
  36730. var colors = [];
  36731. // default face colors and UV if undefined
  36732. for (var f = 0; f < 6; f++) {
  36733. if (faceUV[f] === undefined) {
  36734. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36735. }
  36736. if (faceColors && faceColors[f] === undefined) {
  36737. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36738. }
  36739. }
  36740. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36741. // Create each face in turn.
  36742. for (var index = 0; index < normalsSource.length; index++) {
  36743. var normal = normalsSource[index];
  36744. // Get two vectors perpendicular to the face normal and to each other.
  36745. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36746. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36747. // Six indices (two triangles) per face.
  36748. var verticesLength = positions.length / 3;
  36749. indices.push(verticesLength);
  36750. indices.push(verticesLength + 1);
  36751. indices.push(verticesLength + 2);
  36752. indices.push(verticesLength);
  36753. indices.push(verticesLength + 2);
  36754. indices.push(verticesLength + 3);
  36755. // Four vertices per face.
  36756. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36757. positions.push(vertex.x, vertex.y, vertex.z);
  36758. normals.push(normal.x, normal.y, normal.z);
  36759. uvs.push(faceUV[index].z, faceUV[index].w);
  36760. if (faceColors) {
  36761. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36762. }
  36763. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36764. positions.push(vertex.x, vertex.y, vertex.z);
  36765. normals.push(normal.x, normal.y, normal.z);
  36766. uvs.push(faceUV[index].x, faceUV[index].w);
  36767. if (faceColors) {
  36768. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36769. }
  36770. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36771. positions.push(vertex.x, vertex.y, vertex.z);
  36772. normals.push(normal.x, normal.y, normal.z);
  36773. uvs.push(faceUV[index].x, faceUV[index].y);
  36774. if (faceColors) {
  36775. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36776. }
  36777. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36778. positions.push(vertex.x, vertex.y, vertex.z);
  36779. normals.push(normal.x, normal.y, normal.z);
  36780. uvs.push(faceUV[index].z, faceUV[index].y);
  36781. if (faceColors) {
  36782. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36783. }
  36784. }
  36785. // sides
  36786. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36787. // Result
  36788. var vertexData = new VertexData();
  36789. vertexData.indices = indices;
  36790. vertexData.positions = positions;
  36791. vertexData.normals = normals;
  36792. vertexData.uvs = uvs;
  36793. if (faceColors) {
  36794. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36795. vertexData.colors = totalColors;
  36796. }
  36797. return vertexData;
  36798. };
  36799. /**
  36800. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36801. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36802. * * segments sets the number of horizontal strips optional, default 32
  36803. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36804. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36805. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36806. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36807. * * 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
  36808. * * 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
  36809. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36810. * * 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)
  36811. * * 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)
  36812. * @returns the VertexData of the ellipsoid
  36813. */
  36814. VertexData.CreateSphere = function (options) {
  36815. var segments = options.segments || 32;
  36816. var diameterX = options.diameterX || options.diameter || 1;
  36817. var diameterY = options.diameterY || options.diameter || 1;
  36818. var diameterZ = options.diameterZ || options.diameter || 1;
  36819. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36820. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36821. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36822. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36823. var totalZRotationSteps = 2 + segments;
  36824. var totalYRotationSteps = 2 * totalZRotationSteps;
  36825. var indices = [];
  36826. var positions = [];
  36827. var normals = [];
  36828. var uvs = [];
  36829. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36830. var normalizedZ = zRotationStep / totalZRotationSteps;
  36831. var angleZ = normalizedZ * Math.PI * slice;
  36832. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36833. var normalizedY = yRotationStep / totalYRotationSteps;
  36834. var angleY = normalizedY * Math.PI * 2 * arc;
  36835. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36836. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36837. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36838. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36839. var vertex = complete.multiply(radius);
  36840. var normal = complete.divide(radius).normalize();
  36841. positions.push(vertex.x, vertex.y, vertex.z);
  36842. normals.push(normal.x, normal.y, normal.z);
  36843. uvs.push(normalizedY, normalizedZ);
  36844. }
  36845. if (zRotationStep > 0) {
  36846. var verticesCount = positions.length / 3;
  36847. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36848. indices.push((firstIndex));
  36849. indices.push((firstIndex + 1));
  36850. indices.push(firstIndex + totalYRotationSteps + 1);
  36851. indices.push((firstIndex + totalYRotationSteps + 1));
  36852. indices.push((firstIndex + 1));
  36853. indices.push((firstIndex + totalYRotationSteps + 2));
  36854. }
  36855. }
  36856. }
  36857. // Sides
  36858. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36859. // Result
  36860. var vertexData = new VertexData();
  36861. vertexData.indices = indices;
  36862. vertexData.positions = positions;
  36863. vertexData.normals = normals;
  36864. vertexData.uvs = uvs;
  36865. return vertexData;
  36866. };
  36867. /**
  36868. * Creates the VertexData for a cylinder, cone or prism
  36869. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36870. * * height sets the height (y direction) of the cylinder, optional, default 2
  36871. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36872. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36873. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36874. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36875. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36876. * * 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
  36877. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36878. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36879. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36880. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36881. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36882. * * 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)
  36883. * * 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)
  36884. * @returns the VertexData of the cylinder, cone or prism
  36885. */
  36886. VertexData.CreateCylinder = function (options) {
  36887. var height = options.height || 2;
  36888. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36889. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36890. var tessellation = options.tessellation || 24;
  36891. var subdivisions = options.subdivisions || 1;
  36892. var hasRings = options.hasRings ? true : false;
  36893. var enclose = options.enclose ? true : false;
  36894. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36895. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36896. var faceUV = options.faceUV || new Array(3);
  36897. var faceColors = options.faceColors;
  36898. // default face colors and UV if undefined
  36899. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36900. var ringNb = (hasRings) ? subdivisions : 1;
  36901. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36902. var f;
  36903. for (f = 0; f < surfaceNb; f++) {
  36904. if (faceColors && faceColors[f] === undefined) {
  36905. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36906. }
  36907. }
  36908. for (f = 0; f < surfaceNb; f++) {
  36909. if (faceUV && faceUV[f] === undefined) {
  36910. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36911. }
  36912. }
  36913. var indices = new Array();
  36914. var positions = new Array();
  36915. var normals = new Array();
  36916. var uvs = new Array();
  36917. var colors = new Array();
  36918. var angle_step = Math.PI * 2 * arc / tessellation;
  36919. var angle;
  36920. var h;
  36921. var radius;
  36922. var tan = (diameterBottom - diameterTop) / 2 / height;
  36923. var ringVertex = BABYLON.Vector3.Zero();
  36924. var ringNormal = BABYLON.Vector3.Zero();
  36925. var ringFirstVertex = BABYLON.Vector3.Zero();
  36926. var ringFirstNormal = BABYLON.Vector3.Zero();
  36927. var quadNormal = BABYLON.Vector3.Zero();
  36928. var Y = BABYLON.Axis.Y;
  36929. // positions, normals, uvs
  36930. var i;
  36931. var j;
  36932. var r;
  36933. var ringIdx = 1;
  36934. var s = 1; // surface index
  36935. var cs = 0;
  36936. var v = 0;
  36937. for (i = 0; i <= subdivisions; i++) {
  36938. h = i / subdivisions;
  36939. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36940. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36941. for (r = 0; r < ringIdx; r++) {
  36942. if (hasRings) {
  36943. s += r;
  36944. }
  36945. if (enclose) {
  36946. s += 2 * r;
  36947. }
  36948. for (j = 0; j <= tessellation; j++) {
  36949. angle = j * angle_step;
  36950. // position
  36951. ringVertex.x = Math.cos(-angle) * radius;
  36952. ringVertex.y = -height / 2 + h * height;
  36953. ringVertex.z = Math.sin(-angle) * radius;
  36954. // normal
  36955. if (diameterTop === 0 && i === subdivisions) {
  36956. // if no top cap, reuse former normals
  36957. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36958. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36959. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36960. }
  36961. else {
  36962. ringNormal.x = ringVertex.x;
  36963. ringNormal.z = ringVertex.z;
  36964. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36965. ringNormal.normalize();
  36966. }
  36967. // keep first ring vertex values for enclose
  36968. if (j === 0) {
  36969. ringFirstVertex.copyFrom(ringVertex);
  36970. ringFirstNormal.copyFrom(ringNormal);
  36971. }
  36972. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36973. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36974. if (hasRings) {
  36975. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36976. }
  36977. else {
  36978. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36979. }
  36980. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36981. if (faceColors) {
  36982. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36983. }
  36984. }
  36985. // if enclose, add four vertices and their dedicated normals
  36986. if (arc !== 1 && enclose) {
  36987. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36988. positions.push(0, ringVertex.y, 0);
  36989. positions.push(0, ringVertex.y, 0);
  36990. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36991. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36992. quadNormal.normalize();
  36993. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36994. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36995. quadNormal.normalize();
  36996. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36997. if (hasRings) {
  36998. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36999. }
  37000. else {
  37001. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37002. }
  37003. uvs.push(faceUV[s + 1].x, v);
  37004. uvs.push(faceUV[s + 1].z, v);
  37005. if (hasRings) {
  37006. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37007. }
  37008. else {
  37009. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37010. }
  37011. uvs.push(faceUV[s + 2].x, v);
  37012. uvs.push(faceUV[s + 2].z, v);
  37013. if (faceColors) {
  37014. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37015. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37016. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37017. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37018. }
  37019. }
  37020. if (cs !== s) {
  37021. cs = s;
  37022. }
  37023. }
  37024. }
  37025. // indices
  37026. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37027. var s;
  37028. i = 0;
  37029. for (s = 0; s < subdivisions; s++) {
  37030. var i0 = 0;
  37031. var i1 = 0;
  37032. var i2 = 0;
  37033. var i3 = 0;
  37034. for (j = 0; j < tessellation; j++) {
  37035. i0 = i * (e + 1) + j;
  37036. i1 = (i + 1) * (e + 1) + j;
  37037. i2 = i * (e + 1) + (j + 1);
  37038. i3 = (i + 1) * (e + 1) + (j + 1);
  37039. indices.push(i0, i1, i2);
  37040. indices.push(i3, i2, i1);
  37041. }
  37042. if (arc !== 1 && enclose) { // if enclose, add two quads
  37043. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37044. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37045. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37046. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37047. }
  37048. i = (hasRings) ? (i + 2) : (i + 1);
  37049. }
  37050. // Caps
  37051. var createCylinderCap = function (isTop) {
  37052. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37053. if (radius === 0) {
  37054. return;
  37055. }
  37056. // Cap positions, normals & uvs
  37057. var angle;
  37058. var circleVector;
  37059. var i;
  37060. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37061. var c = null;
  37062. if (faceColors) {
  37063. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37064. }
  37065. // cap center
  37066. var vbase = positions.length / 3;
  37067. var offset = isTop ? height / 2 : -height / 2;
  37068. var center = new BABYLON.Vector3(0, offset, 0);
  37069. positions.push(center.x, center.y, center.z);
  37070. normals.push(0, isTop ? 1 : -1, 0);
  37071. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37072. if (c) {
  37073. colors.push(c.r, c.g, c.b, c.a);
  37074. }
  37075. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37076. for (i = 0; i <= tessellation; i++) {
  37077. angle = Math.PI * 2 * i * arc / tessellation;
  37078. var cos = Math.cos(-angle);
  37079. var sin = Math.sin(-angle);
  37080. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37081. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37082. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37083. normals.push(0, isTop ? 1 : -1, 0);
  37084. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37085. if (c) {
  37086. colors.push(c.r, c.g, c.b, c.a);
  37087. }
  37088. }
  37089. // Cap indices
  37090. for (i = 0; i < tessellation; i++) {
  37091. if (!isTop) {
  37092. indices.push(vbase);
  37093. indices.push(vbase + (i + 1));
  37094. indices.push(vbase + (i + 2));
  37095. }
  37096. else {
  37097. indices.push(vbase);
  37098. indices.push(vbase + (i + 2));
  37099. indices.push(vbase + (i + 1));
  37100. }
  37101. }
  37102. };
  37103. // add caps to geometry
  37104. createCylinderCap(false);
  37105. createCylinderCap(true);
  37106. // Sides
  37107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37108. var vertexData = new VertexData();
  37109. vertexData.indices = indices;
  37110. vertexData.positions = positions;
  37111. vertexData.normals = normals;
  37112. vertexData.uvs = uvs;
  37113. if (faceColors) {
  37114. vertexData.colors = colors;
  37115. }
  37116. return vertexData;
  37117. };
  37118. /**
  37119. * Creates the VertexData for a torus
  37120. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37121. * * diameter the diameter of the torus, optional default 1
  37122. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37123. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37124. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37125. * * 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)
  37126. * * 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)
  37127. * @returns the VertexData of the torus
  37128. */
  37129. VertexData.CreateTorus = function (options) {
  37130. var indices = [];
  37131. var positions = [];
  37132. var normals = [];
  37133. var uvs = [];
  37134. var diameter = options.diameter || 1;
  37135. var thickness = options.thickness || 0.5;
  37136. var tessellation = options.tessellation || 16;
  37137. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37138. var stride = tessellation + 1;
  37139. for (var i = 0; i <= tessellation; i++) {
  37140. var u = i / tessellation;
  37141. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37142. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37143. for (var j = 0; j <= tessellation; j++) {
  37144. var v = 1 - j / tessellation;
  37145. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37146. var dx = Math.cos(innerAngle);
  37147. var dy = Math.sin(innerAngle);
  37148. // Create a vertex.
  37149. var normal = new BABYLON.Vector3(dx, dy, 0);
  37150. var position = normal.scale(thickness / 2);
  37151. var textureCoordinate = new BABYLON.Vector2(u, v);
  37152. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37153. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37154. positions.push(position.x, position.y, position.z);
  37155. normals.push(normal.x, normal.y, normal.z);
  37156. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37157. // And create indices for two triangles.
  37158. var nextI = (i + 1) % stride;
  37159. var nextJ = (j + 1) % stride;
  37160. indices.push(i * stride + j);
  37161. indices.push(i * stride + nextJ);
  37162. indices.push(nextI * stride + j);
  37163. indices.push(i * stride + nextJ);
  37164. indices.push(nextI * stride + nextJ);
  37165. indices.push(nextI * stride + j);
  37166. }
  37167. }
  37168. // Sides
  37169. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37170. // Result
  37171. var vertexData = new VertexData();
  37172. vertexData.indices = indices;
  37173. vertexData.positions = positions;
  37174. vertexData.normals = normals;
  37175. vertexData.uvs = uvs;
  37176. return vertexData;
  37177. };
  37178. /**
  37179. * Creates the VertexData of the LineSystem
  37180. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37181. * - lines an array of lines, each line being an array of successive Vector3
  37182. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37183. * @returns the VertexData of the LineSystem
  37184. */
  37185. VertexData.CreateLineSystem = function (options) {
  37186. var indices = [];
  37187. var positions = [];
  37188. var lines = options.lines;
  37189. var colors = options.colors;
  37190. var vertexColors = [];
  37191. var idx = 0;
  37192. for (var l = 0; l < lines.length; l++) {
  37193. var points = lines[l];
  37194. for (var index = 0; index < points.length; index++) {
  37195. positions.push(points[index].x, points[index].y, points[index].z);
  37196. if (colors) {
  37197. var color = colors[l];
  37198. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37199. }
  37200. if (index > 0) {
  37201. indices.push(idx - 1);
  37202. indices.push(idx);
  37203. }
  37204. idx++;
  37205. }
  37206. }
  37207. var vertexData = new VertexData();
  37208. vertexData.indices = indices;
  37209. vertexData.positions = positions;
  37210. if (colors) {
  37211. vertexData.colors = vertexColors;
  37212. }
  37213. return vertexData;
  37214. };
  37215. /**
  37216. * Create the VertexData for a DashedLines
  37217. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37218. * - points an array successive Vector3
  37219. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37220. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37221. * - dashNb the intended total number of dashes, optional, default 200
  37222. * @returns the VertexData for the DashedLines
  37223. */
  37224. VertexData.CreateDashedLines = function (options) {
  37225. var dashSize = options.dashSize || 3;
  37226. var gapSize = options.gapSize || 1;
  37227. var dashNb = options.dashNb || 200;
  37228. var points = options.points;
  37229. var positions = new Array();
  37230. var indices = new Array();
  37231. var curvect = BABYLON.Vector3.Zero();
  37232. var lg = 0;
  37233. var nb = 0;
  37234. var shft = 0;
  37235. var dashshft = 0;
  37236. var curshft = 0;
  37237. var idx = 0;
  37238. var i = 0;
  37239. for (i = 0; i < points.length - 1; i++) {
  37240. points[i + 1].subtractToRef(points[i], curvect);
  37241. lg += curvect.length();
  37242. }
  37243. shft = lg / dashNb;
  37244. dashshft = dashSize * shft / (dashSize + gapSize);
  37245. for (i = 0; i < points.length - 1; i++) {
  37246. points[i + 1].subtractToRef(points[i], curvect);
  37247. nb = Math.floor(curvect.length() / shft);
  37248. curvect.normalize();
  37249. for (var j = 0; j < nb; j++) {
  37250. curshft = shft * j;
  37251. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37252. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37253. indices.push(idx, idx + 1);
  37254. idx += 2;
  37255. }
  37256. }
  37257. // Result
  37258. var vertexData = new VertexData();
  37259. vertexData.positions = positions;
  37260. vertexData.indices = indices;
  37261. return vertexData;
  37262. };
  37263. /**
  37264. * Creates the VertexData for a Ground
  37265. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37266. * - width the width (x direction) of the ground, optional, default 1
  37267. * - height the height (z direction) of the ground, optional, default 1
  37268. * - subdivisions the number of subdivisions per side, optional, default 1
  37269. * @returns the VertexData of the Ground
  37270. */
  37271. VertexData.CreateGround = function (options) {
  37272. var indices = [];
  37273. var positions = [];
  37274. var normals = [];
  37275. var uvs = [];
  37276. var row, col;
  37277. var width = options.width || 1;
  37278. var height = options.height || 1;
  37279. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37280. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37281. for (row = 0; row <= subdivisionsY; row++) {
  37282. for (col = 0; col <= subdivisionsX; col++) {
  37283. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37284. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37285. positions.push(position.x, position.y, position.z);
  37286. normals.push(normal.x, normal.y, normal.z);
  37287. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37288. }
  37289. }
  37290. for (row = 0; row < subdivisionsY; row++) {
  37291. for (col = 0; col < subdivisionsX; col++) {
  37292. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37293. indices.push(col + 1 + row * (subdivisionsX + 1));
  37294. indices.push(col + row * (subdivisionsX + 1));
  37295. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37296. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37297. indices.push(col + row * (subdivisionsX + 1));
  37298. }
  37299. }
  37300. // Result
  37301. var vertexData = new VertexData();
  37302. vertexData.indices = indices;
  37303. vertexData.positions = positions;
  37304. vertexData.normals = normals;
  37305. vertexData.uvs = uvs;
  37306. return vertexData;
  37307. };
  37308. /**
  37309. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37310. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37311. * * xmin the ground minimum X coordinate, optional, default -1
  37312. * * zmin the ground minimum Z coordinate, optional, default -1
  37313. * * xmax the ground maximum X coordinate, optional, default 1
  37314. * * zmax the ground maximum Z coordinate, optional, default 1
  37315. * * 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}
  37316. * * 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}
  37317. * @returns the VertexData of the TiledGround
  37318. */
  37319. VertexData.CreateTiledGround = function (options) {
  37320. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37321. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37322. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37323. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37324. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37325. var precision = options.precision || { w: 1, h: 1 };
  37326. var indices = new Array();
  37327. var positions = new Array();
  37328. var normals = new Array();
  37329. var uvs = new Array();
  37330. var row, col, tileRow, tileCol;
  37331. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37332. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37333. precision.w = (precision.w < 1) ? 1 : precision.w;
  37334. precision.h = (precision.h < 1) ? 1 : precision.h;
  37335. var tileSize = {
  37336. 'w': (xmax - xmin) / subdivisions.w,
  37337. 'h': (zmax - zmin) / subdivisions.h
  37338. };
  37339. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37340. // Indices
  37341. var base = positions.length / 3;
  37342. var rowLength = precision.w + 1;
  37343. for (row = 0; row < precision.h; row++) {
  37344. for (col = 0; col < precision.w; col++) {
  37345. var square = [
  37346. base + col + row * rowLength,
  37347. base + (col + 1) + row * rowLength,
  37348. base + (col + 1) + (row + 1) * rowLength,
  37349. base + col + (row + 1) * rowLength
  37350. ];
  37351. indices.push(square[1]);
  37352. indices.push(square[2]);
  37353. indices.push(square[3]);
  37354. indices.push(square[0]);
  37355. indices.push(square[1]);
  37356. indices.push(square[3]);
  37357. }
  37358. }
  37359. // Position, normals and uvs
  37360. var position = BABYLON.Vector3.Zero();
  37361. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37362. for (row = 0; row <= precision.h; row++) {
  37363. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37364. for (col = 0; col <= precision.w; col++) {
  37365. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37366. position.y = 0;
  37367. positions.push(position.x, position.y, position.z);
  37368. normals.push(normal.x, normal.y, normal.z);
  37369. uvs.push(col / precision.w, row / precision.h);
  37370. }
  37371. }
  37372. }
  37373. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37374. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37375. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37376. }
  37377. }
  37378. // Result
  37379. var vertexData = new VertexData();
  37380. vertexData.indices = indices;
  37381. vertexData.positions = positions;
  37382. vertexData.normals = normals;
  37383. vertexData.uvs = uvs;
  37384. return vertexData;
  37385. };
  37386. /**
  37387. * Creates the VertexData of the Ground designed from a heightmap
  37388. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37389. * * width the width (x direction) of the ground
  37390. * * height the height (z direction) of the ground
  37391. * * subdivisions the number of subdivisions per side
  37392. * * minHeight the minimum altitude on the ground, optional, default 0
  37393. * * maxHeight the maximum altitude on the ground, optional default 1
  37394. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37395. * * buffer the array holding the image color data
  37396. * * bufferWidth the width of image
  37397. * * bufferHeight the height of image
  37398. * @returns the VertexData of the Ground designed from a heightmap
  37399. */
  37400. VertexData.CreateGroundFromHeightMap = function (options) {
  37401. var indices = [];
  37402. var positions = [];
  37403. var normals = [];
  37404. var uvs = [];
  37405. var row, col;
  37406. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37407. // Vertices
  37408. for (row = 0; row <= options.subdivisions; row++) {
  37409. for (col = 0; col <= options.subdivisions; col++) {
  37410. 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));
  37411. // Compute height
  37412. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37413. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37414. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37415. var r = options.buffer[pos] / 255.0;
  37416. var g = options.buffer[pos + 1] / 255.0;
  37417. var b = options.buffer[pos + 2] / 255.0;
  37418. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37419. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37420. // Add vertex
  37421. positions.push(position.x, position.y, position.z);
  37422. normals.push(0, 0, 0);
  37423. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37424. }
  37425. }
  37426. // Indices
  37427. for (row = 0; row < options.subdivisions; row++) {
  37428. for (col = 0; col < options.subdivisions; col++) {
  37429. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37430. indices.push(col + 1 + row * (options.subdivisions + 1));
  37431. indices.push(col + row * (options.subdivisions + 1));
  37432. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37433. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37434. indices.push(col + row * (options.subdivisions + 1));
  37435. }
  37436. }
  37437. // Normals
  37438. VertexData.ComputeNormals(positions, indices, normals);
  37439. // Result
  37440. var vertexData = new VertexData();
  37441. vertexData.indices = indices;
  37442. vertexData.positions = positions;
  37443. vertexData.normals = normals;
  37444. vertexData.uvs = uvs;
  37445. return vertexData;
  37446. };
  37447. /**
  37448. * Creates the VertexData for a Plane
  37449. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37450. * * size sets the width and height of the plane to the value of size, optional default 1
  37451. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37452. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37453. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37454. * * 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)
  37455. * * 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)
  37456. * @returns the VertexData of the box
  37457. */
  37458. VertexData.CreatePlane = function (options) {
  37459. var indices = [];
  37460. var positions = [];
  37461. var normals = [];
  37462. var uvs = [];
  37463. var width = options.width || options.size || 1;
  37464. var height = options.height || options.size || 1;
  37465. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37466. // Vertices
  37467. var halfWidth = width / 2.0;
  37468. var halfHeight = height / 2.0;
  37469. positions.push(-halfWidth, -halfHeight, 0);
  37470. normals.push(0, 0, -1.0);
  37471. uvs.push(0.0, 0.0);
  37472. positions.push(halfWidth, -halfHeight, 0);
  37473. normals.push(0, 0, -1.0);
  37474. uvs.push(1.0, 0.0);
  37475. positions.push(halfWidth, halfHeight, 0);
  37476. normals.push(0, 0, -1.0);
  37477. uvs.push(1.0, 1.0);
  37478. positions.push(-halfWidth, halfHeight, 0);
  37479. normals.push(0, 0, -1.0);
  37480. uvs.push(0.0, 1.0);
  37481. // Indices
  37482. indices.push(0);
  37483. indices.push(1);
  37484. indices.push(2);
  37485. indices.push(0);
  37486. indices.push(2);
  37487. indices.push(3);
  37488. // Sides
  37489. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37490. // Result
  37491. var vertexData = new VertexData();
  37492. vertexData.indices = indices;
  37493. vertexData.positions = positions;
  37494. vertexData.normals = normals;
  37495. vertexData.uvs = uvs;
  37496. return vertexData;
  37497. };
  37498. /**
  37499. * Creates the VertexData of the Disc or regular Polygon
  37500. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37501. * * radius the radius of the disc, optional default 0.5
  37502. * * tessellation the number of polygon sides, optional, default 64
  37503. * * 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
  37504. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37505. * * 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)
  37506. * * 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)
  37507. * @returns the VertexData of the box
  37508. */
  37509. VertexData.CreateDisc = function (options) {
  37510. var positions = new Array();
  37511. var indices = new Array();
  37512. var normals = new Array();
  37513. var uvs = new Array();
  37514. var radius = options.radius || 0.5;
  37515. var tessellation = options.tessellation || 64;
  37516. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37517. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37518. // positions and uvs
  37519. positions.push(0, 0, 0); // disc center first
  37520. uvs.push(0.5, 0.5);
  37521. var theta = Math.PI * 2 * arc;
  37522. var step = theta / tessellation;
  37523. for (var a = 0; a < theta; a += step) {
  37524. var x = Math.cos(a);
  37525. var y = Math.sin(a);
  37526. var u = (x + 1) / 2;
  37527. var v = (1 - y) / 2;
  37528. positions.push(radius * x, radius * y, 0);
  37529. uvs.push(u, v);
  37530. }
  37531. if (arc === 1) {
  37532. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37533. uvs.push(uvs[2], uvs[3]);
  37534. }
  37535. //indices
  37536. var vertexNb = positions.length / 3;
  37537. for (var i = 1; i < vertexNb - 1; i++) {
  37538. indices.push(i + 1, 0, i);
  37539. }
  37540. // result
  37541. VertexData.ComputeNormals(positions, indices, normals);
  37542. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37543. var vertexData = new VertexData();
  37544. vertexData.indices = indices;
  37545. vertexData.positions = positions;
  37546. vertexData.normals = normals;
  37547. vertexData.uvs = uvs;
  37548. return vertexData;
  37549. };
  37550. /**
  37551. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37552. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37553. * @param polygon a mesh built from polygonTriangulation.build()
  37554. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37555. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37556. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37557. * @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)
  37558. * @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)
  37559. * @returns the VertexData of the Polygon
  37560. */
  37561. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37562. var faceUV = fUV || new Array(3);
  37563. var faceColors = fColors;
  37564. var colors = [];
  37565. // default face colors and UV if undefined
  37566. for (var f = 0; f < 3; f++) {
  37567. if (faceUV[f] === undefined) {
  37568. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37569. }
  37570. if (faceColors && faceColors[f] === undefined) {
  37571. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37572. }
  37573. }
  37574. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37575. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37576. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37577. var indices = polygon.getIndices();
  37578. // set face colours and textures
  37579. var idx = 0;
  37580. var face = 0;
  37581. for (var index = 0; index < normals.length; index += 3) {
  37582. //Edge Face no. 1
  37583. if (Math.abs(normals[index + 1]) < 0.001) {
  37584. face = 1;
  37585. }
  37586. //Top Face no. 0
  37587. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37588. face = 0;
  37589. }
  37590. //Bottom Face no. 2
  37591. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37592. face = 2;
  37593. }
  37594. idx = index / 3;
  37595. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37596. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37597. if (faceColors) {
  37598. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37599. }
  37600. }
  37601. // sides
  37602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37603. // Result
  37604. var vertexData = new VertexData();
  37605. vertexData.indices = indices;
  37606. vertexData.positions = positions;
  37607. vertexData.normals = normals;
  37608. vertexData.uvs = uvs;
  37609. if (faceColors) {
  37610. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37611. vertexData.colors = totalColors;
  37612. }
  37613. return vertexData;
  37614. };
  37615. /**
  37616. * Creates the VertexData of the IcoSphere
  37617. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37618. * * radius the radius of the IcoSphere, optional default 1
  37619. * * radiusX allows stretching in the x direction, optional, default radius
  37620. * * radiusY allows stretching in the y direction, optional, default radius
  37621. * * radiusZ allows stretching in the z direction, optional, default radius
  37622. * * flat when true creates a flat shaded mesh, optional, default true
  37623. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37624. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37625. * * 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)
  37626. * * 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)
  37627. * @returns the VertexData of the IcoSphere
  37628. */
  37629. VertexData.CreateIcoSphere = function (options) {
  37630. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37631. var radius = options.radius || 1;
  37632. var flat = (options.flat === undefined) ? true : options.flat;
  37633. var subdivisions = options.subdivisions || 4;
  37634. var radiusX = options.radiusX || radius;
  37635. var radiusY = options.radiusY || radius;
  37636. var radiusZ = options.radiusZ || radius;
  37637. var t = (1 + Math.sqrt(5)) / 2;
  37638. // 12 vertex x,y,z
  37639. var ico_vertices = [
  37640. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37641. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37642. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37643. ];
  37644. // index of 3 vertex makes a face of icopshere
  37645. var ico_indices = [
  37646. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37647. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37648. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37649. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37650. ];
  37651. // vertex for uv have aliased position, not for UV
  37652. var vertices_unalias_id = [
  37653. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37654. // vertex alias
  37655. 0,
  37656. 2,
  37657. 3,
  37658. 3,
  37659. 3,
  37660. 4,
  37661. 7,
  37662. 8,
  37663. 9,
  37664. 9,
  37665. 10,
  37666. 11 // 23: B + 12
  37667. ];
  37668. // uv as integer step (not pixels !)
  37669. var ico_vertexuv = [
  37670. 5, 1, 3, 1, 6, 4, 0, 0,
  37671. 5, 3, 4, 2, 2, 2, 4, 0,
  37672. 2, 0, 1, 1, 6, 0, 6, 2,
  37673. // vertex alias (for same vertex on different faces)
  37674. 0, 4,
  37675. 3, 3,
  37676. 4, 4,
  37677. 3, 1,
  37678. 4, 2,
  37679. 4, 4,
  37680. 0, 2,
  37681. 1, 1,
  37682. 2, 2,
  37683. 3, 3,
  37684. 1, 3,
  37685. 2, 4 // 23: B + 12
  37686. ];
  37687. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37688. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37689. // First island of uv mapping
  37690. // v = 4h 3+ 2
  37691. // v = 3h 9+ 4
  37692. // v = 2h 9+ 5 B
  37693. // v = 1h 9 1 0
  37694. // v = 0h 3 8 7 A
  37695. // u = 0 1 2 3 4 5 6 *a
  37696. // Second island of uv mapping
  37697. // v = 4h 0+ B+ 4+
  37698. // v = 3h A+ 2+
  37699. // v = 2h 7+ 6 3+
  37700. // v = 1h 8+ 3+
  37701. // v = 0h
  37702. // u = 0 1 2 3 4 5 6 *a
  37703. // Face layout on texture UV mapping
  37704. // ============
  37705. // \ 4 /\ 16 / ======
  37706. // \ / \ / /\ 11 /
  37707. // \/ 7 \/ / \ /
  37708. // ======= / 10 \/
  37709. // /\ 17 /\ =======
  37710. // / \ / \ \ 15 /\
  37711. // / 8 \/ 12 \ \ / \
  37712. // ============ \/ 6 \
  37713. // \ 18 /\ ============
  37714. // \ / \ \ 5 /\ 0 /
  37715. // \/ 13 \ \ / \ /
  37716. // ======= \/ 1 \/
  37717. // =============
  37718. // /\ 19 /\ 2 /\
  37719. // / \ / \ / \
  37720. // / 14 \/ 9 \/ 3 \
  37721. // ===================
  37722. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37723. var ustep = 138 / 1024;
  37724. var vstep = 239 / 1024;
  37725. var uoffset = 60 / 1024;
  37726. var voffset = 26 / 1024;
  37727. // Second island should have margin, not to touch the first island
  37728. // avoid any borderline artefact in pixel rounding
  37729. var island_u_offset = -40 / 1024;
  37730. var island_v_offset = +20 / 1024;
  37731. // face is either island 0 or 1 :
  37732. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37733. var island = [
  37734. 0, 0, 0, 0, 1,
  37735. 0, 0, 1, 1, 0,
  37736. 0, 0, 1, 1, 0,
  37737. 0, 1, 1, 1, 0 // 15 - 19
  37738. ];
  37739. var indices = new Array();
  37740. var positions = new Array();
  37741. var normals = new Array();
  37742. var uvs = new Array();
  37743. var current_indice = 0;
  37744. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37745. var face_vertex_pos = new Array(3);
  37746. var face_vertex_uv = new Array(3);
  37747. var v012;
  37748. for (v012 = 0; v012 < 3; v012++) {
  37749. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37750. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37751. }
  37752. // create all with normals
  37753. for (var face = 0; face < 20; face++) {
  37754. // 3 vertex per face
  37755. for (v012 = 0; v012 < 3; v012++) {
  37756. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37757. var v_id = ico_indices[3 * face + v012];
  37758. // vertex have 3D position (x,y,z)
  37759. 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]);
  37760. // Normalize to get normal, then scale to radius
  37761. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37762. // uv Coordinates from vertex ID
  37763. 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);
  37764. }
  37765. // Subdivide the face (interpolate pos, norm, uv)
  37766. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37767. // - norm is linear interpolation of vertex corner normal
  37768. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37769. // - uv is linear interpolation
  37770. //
  37771. // Topology is as below for sub-divide by 2
  37772. // vertex shown as v0,v1,v2
  37773. // interp index is i1 to progress in range [v0,v1[
  37774. // interp index is i2 to progress in range [v0,v2[
  37775. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37776. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37777. //
  37778. //
  37779. // i2 v2
  37780. // ^ ^
  37781. // / / \
  37782. // / / \
  37783. // / / \
  37784. // / / (0,1) \
  37785. // / #---------\
  37786. // / / \ (0,0)'/ \
  37787. // / / \ / \
  37788. // / / \ / \
  37789. // / / (0,0) \ / (1,0) \
  37790. // / #---------#---------\
  37791. // v0 v1
  37792. //
  37793. // --------------------> i1
  37794. //
  37795. // interp of (i1,i2):
  37796. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37797. // along i1 : lerp(x0,x1, i1/(S-i2))
  37798. //
  37799. // centroid of triangle is needed to get help normal computation
  37800. // (c1,c2) are used for centroid location
  37801. var interp_vertex = function (i1, i2, c1, c2) {
  37802. // vertex is interpolated from
  37803. // - face_vertex_pos[0..2]
  37804. // - face_vertex_uv[0..2]
  37805. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37806. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37807. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37808. pos_interp.normalize();
  37809. var vertex_normal;
  37810. if (flat) {
  37811. // in flat mode, recalculate normal as face centroid normal
  37812. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37813. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37814. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37815. }
  37816. else {
  37817. // in smooth mode, recalculate normal from each single vertex position
  37818. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37819. }
  37820. // Vertex normal need correction due to X,Y,Z radius scaling
  37821. vertex_normal.x /= radiusX;
  37822. vertex_normal.y /= radiusY;
  37823. vertex_normal.z /= radiusZ;
  37824. vertex_normal.normalize();
  37825. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37826. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37827. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37828. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37829. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37830. uvs.push(uv_interp.x, uv_interp.y);
  37831. // push each vertex has member of a face
  37832. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37833. indices.push(current_indice);
  37834. current_indice++;
  37835. };
  37836. for (var i2 = 0; i2 < subdivisions; i2++) {
  37837. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37838. // face : (i1,i2) for /\ :
  37839. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37840. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37841. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37842. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37843. if (i1 + i2 + 1 < subdivisions) {
  37844. // face : (i1,i2)' for \/ :
  37845. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37846. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37847. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37848. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37849. }
  37850. }
  37851. }
  37852. }
  37853. // Sides
  37854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37855. // Result
  37856. var vertexData = new VertexData();
  37857. vertexData.indices = indices;
  37858. vertexData.positions = positions;
  37859. vertexData.normals = normals;
  37860. vertexData.uvs = uvs;
  37861. return vertexData;
  37862. };
  37863. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37864. /**
  37865. * Creates the VertexData for a Polyhedron
  37866. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37867. * * type provided types are:
  37868. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37869. * * 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)
  37870. * * size the size of the IcoSphere, optional default 1
  37871. * * sizeX allows stretching in the x direction, optional, default size
  37872. * * sizeY allows stretching in the y direction, optional, default size
  37873. * * sizeZ allows stretching in the z direction, optional, default size
  37874. * * 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
  37875. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37876. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37877. * * flat when true creates a flat shaded mesh, optional, default true
  37878. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37879. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37880. * * 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)
  37881. * * 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)
  37882. * @returns the VertexData of the Polyhedron
  37883. */
  37884. VertexData.CreatePolyhedron = function (options) {
  37885. // provided polyhedron types :
  37886. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37887. // 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)
  37888. var polyhedra = [];
  37889. 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]] };
  37890. 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]] };
  37891. polyhedra[2] = {
  37892. 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]],
  37893. 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]]
  37894. };
  37895. polyhedra[3] = {
  37896. 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]],
  37897. 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]]
  37898. };
  37899. polyhedra[4] = {
  37900. 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]],
  37901. 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]]
  37902. };
  37903. 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]] };
  37904. 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]] };
  37905. 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]] };
  37906. 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]] };
  37907. 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]] };
  37908. 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]] };
  37909. 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]] };
  37910. 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]] };
  37911. 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]] };
  37912. polyhedra[14] = {
  37913. 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]],
  37914. 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]]
  37915. };
  37916. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37917. var size = options.size;
  37918. var sizeX = options.sizeX || size || 1;
  37919. var sizeY = options.sizeY || size || 1;
  37920. var sizeZ = options.sizeZ || size || 1;
  37921. var data = options.custom || polyhedra[type];
  37922. var nbfaces = data.face.length;
  37923. var faceUV = options.faceUV || new Array(nbfaces);
  37924. var faceColors = options.faceColors;
  37925. var flat = (options.flat === undefined) ? true : options.flat;
  37926. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37927. var positions = new Array();
  37928. var indices = new Array();
  37929. var normals = new Array();
  37930. var uvs = new Array();
  37931. var colors = new Array();
  37932. var index = 0;
  37933. var faceIdx = 0; // face cursor in the array "indexes"
  37934. var indexes = new Array();
  37935. var i = 0;
  37936. var f = 0;
  37937. var u, v, ang, x, y, tmp;
  37938. // default face colors and UV if undefined
  37939. if (flat) {
  37940. for (f = 0; f < nbfaces; f++) {
  37941. if (faceColors && faceColors[f] === undefined) {
  37942. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37943. }
  37944. if (faceUV && faceUV[f] === undefined) {
  37945. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37946. }
  37947. }
  37948. }
  37949. if (!flat) {
  37950. for (i = 0; i < data.vertex.length; i++) {
  37951. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37952. uvs.push(0, 0);
  37953. }
  37954. for (f = 0; f < nbfaces; f++) {
  37955. for (i = 0; i < data.face[f].length - 2; i++) {
  37956. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37957. }
  37958. }
  37959. }
  37960. else {
  37961. for (f = 0; f < nbfaces; f++) {
  37962. var fl = data.face[f].length; // number of vertices of the current face
  37963. ang = 2 * Math.PI / fl;
  37964. x = 0.5 * Math.tan(ang / 2);
  37965. y = 0.5;
  37966. // positions, uvs, colors
  37967. for (i = 0; i < fl; i++) {
  37968. // positions
  37969. 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);
  37970. indexes.push(index);
  37971. index++;
  37972. // uvs
  37973. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37974. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37975. uvs.push(u, v);
  37976. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37977. y = x * Math.sin(ang) + y * Math.cos(ang);
  37978. x = tmp;
  37979. // colors
  37980. if (faceColors) {
  37981. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37982. }
  37983. }
  37984. // indices from indexes
  37985. for (i = 0; i < fl - 2; i++) {
  37986. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37987. }
  37988. faceIdx += fl;
  37989. }
  37990. }
  37991. VertexData.ComputeNormals(positions, indices, normals);
  37992. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37993. var vertexData = new VertexData();
  37994. vertexData.positions = positions;
  37995. vertexData.indices = indices;
  37996. vertexData.normals = normals;
  37997. vertexData.uvs = uvs;
  37998. if (faceColors && flat) {
  37999. vertexData.colors = colors;
  38000. }
  38001. return vertexData;
  38002. };
  38003. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38004. /**
  38005. * Creates the VertexData for a TorusKnot
  38006. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38007. * * radius the radius of the torus knot, optional, default 2
  38008. * * tube the thickness of the tube, optional, default 0.5
  38009. * * radialSegments the number of sides on each tube segments, optional, default 32
  38010. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38011. * * p the number of windings around the z axis, optional, default 2
  38012. * * q the number of windings around the x axis, optional, default 3
  38013. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38014. * * 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)
  38015. * * 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)
  38016. * @returns the VertexData of the Torus Knot
  38017. */
  38018. VertexData.CreateTorusKnot = function (options) {
  38019. var indices = new Array();
  38020. var positions = new Array();
  38021. var normals = new Array();
  38022. var uvs = new Array();
  38023. var radius = options.radius || 2;
  38024. var tube = options.tube || 0.5;
  38025. var radialSegments = options.radialSegments || 32;
  38026. var tubularSegments = options.tubularSegments || 32;
  38027. var p = options.p || 2;
  38028. var q = options.q || 3;
  38029. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38030. // Helper
  38031. var getPos = function (angle) {
  38032. var cu = Math.cos(angle);
  38033. var su = Math.sin(angle);
  38034. var quOverP = q / p * angle;
  38035. var cs = Math.cos(quOverP);
  38036. var tx = radius * (2 + cs) * 0.5 * cu;
  38037. var ty = radius * (2 + cs) * su * 0.5;
  38038. var tz = radius * Math.sin(quOverP) * 0.5;
  38039. return new BABYLON.Vector3(tx, ty, tz);
  38040. };
  38041. // Vertices
  38042. var i;
  38043. var j;
  38044. for (i = 0; i <= radialSegments; i++) {
  38045. var modI = i % radialSegments;
  38046. var u = modI / radialSegments * 2 * p * Math.PI;
  38047. var p1 = getPos(u);
  38048. var p2 = getPos(u + 0.01);
  38049. var tang = p2.subtract(p1);
  38050. var n = p2.add(p1);
  38051. var bitan = BABYLON.Vector3.Cross(tang, n);
  38052. n = BABYLON.Vector3.Cross(bitan, tang);
  38053. bitan.normalize();
  38054. n.normalize();
  38055. for (j = 0; j < tubularSegments; j++) {
  38056. var modJ = j % tubularSegments;
  38057. var v = modJ / tubularSegments * 2 * Math.PI;
  38058. var cx = -tube * Math.cos(v);
  38059. var cy = tube * Math.sin(v);
  38060. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38061. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38062. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38063. uvs.push(i / radialSegments);
  38064. uvs.push(j / tubularSegments);
  38065. }
  38066. }
  38067. for (i = 0; i < radialSegments; i++) {
  38068. for (j = 0; j < tubularSegments; j++) {
  38069. var jNext = (j + 1) % tubularSegments;
  38070. var a = i * tubularSegments + j;
  38071. var b = (i + 1) * tubularSegments + j;
  38072. var c = (i + 1) * tubularSegments + jNext;
  38073. var d = i * tubularSegments + jNext;
  38074. indices.push(d);
  38075. indices.push(b);
  38076. indices.push(a);
  38077. indices.push(d);
  38078. indices.push(c);
  38079. indices.push(b);
  38080. }
  38081. }
  38082. // Normals
  38083. VertexData.ComputeNormals(positions, indices, normals);
  38084. // Sides
  38085. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38086. // Result
  38087. var vertexData = new VertexData();
  38088. vertexData.indices = indices;
  38089. vertexData.positions = positions;
  38090. vertexData.normals = normals;
  38091. vertexData.uvs = uvs;
  38092. return vertexData;
  38093. };
  38094. // Tools
  38095. /**
  38096. * Compute normals for given positions and indices
  38097. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38098. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38099. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38100. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38101. * * facetNormals : optional array of facet normals (vector3)
  38102. * * facetPositions : optional array of facet positions (vector3)
  38103. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38104. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38105. * * bInfo : optional bounding info, required for facetPartitioning computation
  38106. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38107. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38108. * * useRightHandedSystem: optional boolean to for right handed system computation
  38109. * * depthSort : optional boolean to enable the facet depth sort computation
  38110. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38111. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38112. */
  38113. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38114. // temporary scalar variables
  38115. var index = 0; // facet index
  38116. var p1p2x = 0.0; // p1p2 vector x coordinate
  38117. var p1p2y = 0.0; // p1p2 vector y coordinate
  38118. var p1p2z = 0.0; // p1p2 vector z coordinate
  38119. var p3p2x = 0.0; // p3p2 vector x coordinate
  38120. var p3p2y = 0.0; // p3p2 vector y coordinate
  38121. var p3p2z = 0.0; // p3p2 vector z coordinate
  38122. var faceNormalx = 0.0; // facet normal x coordinate
  38123. var faceNormaly = 0.0; // facet normal y coordinate
  38124. var faceNormalz = 0.0; // facet normal z coordinate
  38125. var length = 0.0; // facet normal length before normalization
  38126. var v1x = 0; // vector1 x index in the positions array
  38127. var v1y = 0; // vector1 y index in the positions array
  38128. var v1z = 0; // vector1 z index in the positions array
  38129. var v2x = 0; // vector2 x index in the positions array
  38130. var v2y = 0; // vector2 y index in the positions array
  38131. var v2z = 0; // vector2 z index in the positions array
  38132. var v3x = 0; // vector3 x index in the positions array
  38133. var v3y = 0; // vector3 y index in the positions array
  38134. var v3z = 0; // vector3 z index in the positions array
  38135. var computeFacetNormals = false;
  38136. var computeFacetPositions = false;
  38137. var computeFacetPartitioning = false;
  38138. var computeDepthSort = false;
  38139. var faceNormalSign = 1;
  38140. var ratio = 0;
  38141. var distanceTo = null;
  38142. if (options) {
  38143. computeFacetNormals = (options.facetNormals) ? true : false;
  38144. computeFacetPositions = (options.facetPositions) ? true : false;
  38145. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38146. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38147. ratio = options.ratio || 0;
  38148. computeDepthSort = (options.depthSort) ? true : false;
  38149. distanceTo = (options.distanceTo);
  38150. if (computeDepthSort) {
  38151. if (distanceTo === undefined) {
  38152. distanceTo = BABYLON.Vector3.Zero();
  38153. }
  38154. var depthSortedFacets = options.depthSortedFacets;
  38155. }
  38156. }
  38157. // facetPartitioning reinit if needed
  38158. var xSubRatio = 0;
  38159. var ySubRatio = 0;
  38160. var zSubRatio = 0;
  38161. var subSq = 0;
  38162. if (computeFacetPartitioning && options && options.bbSize) {
  38163. var ox = 0; // X partitioning index for facet position
  38164. var oy = 0; // Y partinioning index for facet position
  38165. var oz = 0; // Z partinioning index for facet position
  38166. var b1x = 0; // X partitioning index for facet v1 vertex
  38167. var b1y = 0; // Y partitioning index for facet v1 vertex
  38168. var b1z = 0; // z partitioning index for facet v1 vertex
  38169. var b2x = 0; // X partitioning index for facet v2 vertex
  38170. var b2y = 0; // Y partitioning index for facet v2 vertex
  38171. var b2z = 0; // Z partitioning index for facet v2 vertex
  38172. var b3x = 0; // X partitioning index for facet v3 vertex
  38173. var b3y = 0; // Y partitioning index for facet v3 vertex
  38174. var b3z = 0; // Z partitioning index for facet v3 vertex
  38175. var block_idx_o = 0; // facet barycenter block index
  38176. var block_idx_v1 = 0; // v1 vertex block index
  38177. var block_idx_v2 = 0; // v2 vertex block index
  38178. var block_idx_v3 = 0; // v3 vertex block index
  38179. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38180. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38181. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38182. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38183. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38184. subSq = options.subDiv.max * options.subDiv.max;
  38185. options.facetPartitioning.length = 0;
  38186. }
  38187. // reset the normals
  38188. for (index = 0; index < positions.length; index++) {
  38189. normals[index] = 0.0;
  38190. }
  38191. // Loop : 1 indice triplet = 1 facet
  38192. var nbFaces = (indices.length / 3) | 0;
  38193. for (index = 0; index < nbFaces; index++) {
  38194. // get the indexes of the coordinates of each vertex of the facet
  38195. v1x = indices[index * 3] * 3;
  38196. v1y = v1x + 1;
  38197. v1z = v1x + 2;
  38198. v2x = indices[index * 3 + 1] * 3;
  38199. v2y = v2x + 1;
  38200. v2z = v2x + 2;
  38201. v3x = indices[index * 3 + 2] * 3;
  38202. v3y = v3x + 1;
  38203. v3z = v3x + 2;
  38204. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38205. p1p2y = positions[v1y] - positions[v2y];
  38206. p1p2z = positions[v1z] - positions[v2z];
  38207. p3p2x = positions[v3x] - positions[v2x];
  38208. p3p2y = positions[v3y] - positions[v2y];
  38209. p3p2z = positions[v3z] - positions[v2z];
  38210. // compute the face normal with the cross product
  38211. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38212. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38213. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38214. // normalize this normal and store it in the array facetData
  38215. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38216. length = (length === 0) ? 1.0 : length;
  38217. faceNormalx /= length;
  38218. faceNormaly /= length;
  38219. faceNormalz /= length;
  38220. if (computeFacetNormals && options) {
  38221. options.facetNormals[index].x = faceNormalx;
  38222. options.facetNormals[index].y = faceNormaly;
  38223. options.facetNormals[index].z = faceNormalz;
  38224. }
  38225. if (computeFacetPositions && options) {
  38226. // compute and the facet barycenter coordinates in the array facetPositions
  38227. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38228. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38229. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38230. }
  38231. if (computeFacetPartitioning && options) {
  38232. // store the facet indexes in arrays in the main facetPartitioning array :
  38233. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38234. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38235. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38236. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38237. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38238. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38239. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38240. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38241. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38242. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38243. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38244. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38245. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38246. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38247. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38248. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38249. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38250. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38251. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38252. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38253. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38254. // push each facet index in each block containing the vertex
  38255. options.facetPartitioning[block_idx_v1].push(index);
  38256. if (block_idx_v2 != block_idx_v1) {
  38257. options.facetPartitioning[block_idx_v2].push(index);
  38258. }
  38259. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38260. options.facetPartitioning[block_idx_v3].push(index);
  38261. }
  38262. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38263. options.facetPartitioning[block_idx_o].push(index);
  38264. }
  38265. }
  38266. if (computeDepthSort && options && options.facetPositions) {
  38267. var dsf = depthSortedFacets[index];
  38268. dsf.ind = index * 3;
  38269. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38270. }
  38271. // compute the normals anyway
  38272. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38273. normals[v1y] += faceNormaly;
  38274. normals[v1z] += faceNormalz;
  38275. normals[v2x] += faceNormalx;
  38276. normals[v2y] += faceNormaly;
  38277. normals[v2z] += faceNormalz;
  38278. normals[v3x] += faceNormalx;
  38279. normals[v3y] += faceNormaly;
  38280. normals[v3z] += faceNormalz;
  38281. }
  38282. // last normalization of each normal
  38283. for (index = 0; index < normals.length / 3; index++) {
  38284. faceNormalx = normals[index * 3];
  38285. faceNormaly = normals[index * 3 + 1];
  38286. faceNormalz = normals[index * 3 + 2];
  38287. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38288. length = (length === 0) ? 1.0 : length;
  38289. faceNormalx /= length;
  38290. faceNormaly /= length;
  38291. faceNormalz /= length;
  38292. normals[index * 3] = faceNormalx;
  38293. normals[index * 3 + 1] = faceNormaly;
  38294. normals[index * 3 + 2] = faceNormalz;
  38295. }
  38296. };
  38297. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38298. var li = indices.length;
  38299. var ln = normals.length;
  38300. var i;
  38301. var n;
  38302. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38303. switch (sideOrientation) {
  38304. case BABYLON.Mesh.FRONTSIDE:
  38305. // nothing changed
  38306. break;
  38307. case BABYLON.Mesh.BACKSIDE:
  38308. var tmp;
  38309. // indices
  38310. for (i = 0; i < li; i += 3) {
  38311. tmp = indices[i];
  38312. indices[i] = indices[i + 2];
  38313. indices[i + 2] = tmp;
  38314. }
  38315. // normals
  38316. for (n = 0; n < ln; n++) {
  38317. normals[n] = -normals[n];
  38318. }
  38319. break;
  38320. case BABYLON.Mesh.DOUBLESIDE:
  38321. // positions
  38322. var lp = positions.length;
  38323. var l = lp / 3;
  38324. for (var p = 0; p < lp; p++) {
  38325. positions[lp + p] = positions[p];
  38326. }
  38327. // indices
  38328. for (i = 0; i < li; i += 3) {
  38329. indices[i + li] = indices[i + 2] + l;
  38330. indices[i + 1 + li] = indices[i + 1] + l;
  38331. indices[i + 2 + li] = indices[i] + l;
  38332. }
  38333. // normals
  38334. for (n = 0; n < ln; n++) {
  38335. normals[ln + n] = -normals[n];
  38336. }
  38337. // uvs
  38338. var lu = uvs.length;
  38339. var u = 0;
  38340. for (u = 0; u < lu; u++) {
  38341. uvs[u + lu] = uvs[u];
  38342. }
  38343. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38344. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38345. u = 0;
  38346. for (i = 0; i < lu / 2; i++) {
  38347. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38348. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38349. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38350. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38351. u += 2;
  38352. }
  38353. break;
  38354. }
  38355. };
  38356. /**
  38357. * Applies VertexData created from the imported parameters to the geometry
  38358. * @param parsedVertexData the parsed data from an imported file
  38359. * @param geometry the geometry to apply the VertexData to
  38360. */
  38361. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38362. var vertexData = new VertexData();
  38363. // positions
  38364. var positions = parsedVertexData.positions;
  38365. if (positions) {
  38366. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38367. }
  38368. // normals
  38369. var normals = parsedVertexData.normals;
  38370. if (normals) {
  38371. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38372. }
  38373. // tangents
  38374. var tangents = parsedVertexData.tangents;
  38375. if (tangents) {
  38376. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38377. }
  38378. // uvs
  38379. var uvs = parsedVertexData.uvs;
  38380. if (uvs) {
  38381. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38382. }
  38383. // uv2s
  38384. var uv2s = parsedVertexData.uv2s;
  38385. if (uv2s) {
  38386. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38387. }
  38388. // uv3s
  38389. var uv3s = parsedVertexData.uv3s;
  38390. if (uv3s) {
  38391. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38392. }
  38393. // uv4s
  38394. var uv4s = parsedVertexData.uv4s;
  38395. if (uv4s) {
  38396. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38397. }
  38398. // uv5s
  38399. var uv5s = parsedVertexData.uv5s;
  38400. if (uv5s) {
  38401. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38402. }
  38403. // uv6s
  38404. var uv6s = parsedVertexData.uv6s;
  38405. if (uv6s) {
  38406. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38407. }
  38408. // colors
  38409. var colors = parsedVertexData.colors;
  38410. if (colors) {
  38411. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38412. }
  38413. // matricesIndices
  38414. var matricesIndices = parsedVertexData.matricesIndices;
  38415. if (matricesIndices) {
  38416. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38417. }
  38418. // matricesWeights
  38419. var matricesWeights = parsedVertexData.matricesWeights;
  38420. if (matricesWeights) {
  38421. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38422. }
  38423. // indices
  38424. var indices = parsedVertexData.indices;
  38425. if (indices) {
  38426. vertexData.indices = indices;
  38427. }
  38428. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38429. };
  38430. return VertexData;
  38431. }());
  38432. BABYLON.VertexData = VertexData;
  38433. })(BABYLON || (BABYLON = {}));
  38434. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38435. var BABYLON;
  38436. (function (BABYLON) {
  38437. /**
  38438. * Class used to store geometry data (vertex buffers + index buffer)
  38439. */
  38440. var Geometry = /** @class */ (function () {
  38441. /**
  38442. * Creates a new geometry
  38443. * @param id defines the unique ID
  38444. * @param scene defines the hosting scene
  38445. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38446. * @param updatable defines if geometry must be updatable (false by default)
  38447. * @param mesh defines the mesh that will be associated with the geometry
  38448. */
  38449. function Geometry(id, scene, vertexData, updatable, mesh) {
  38450. if (updatable === void 0) { updatable = false; }
  38451. if (mesh === void 0) { mesh = null; }
  38452. /**
  38453. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38454. */
  38455. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38456. this._totalVertices = 0;
  38457. this._isDisposed = false;
  38458. this._indexBufferIsUpdatable = false;
  38459. this.id = id;
  38460. this._engine = scene.getEngine();
  38461. this._meshes = [];
  38462. this._scene = scene;
  38463. //Init vertex buffer cache
  38464. this._vertexBuffers = {};
  38465. this._indices = [];
  38466. this._updatable = updatable;
  38467. // vertexData
  38468. if (vertexData) {
  38469. this.setAllVerticesData(vertexData, updatable);
  38470. }
  38471. else {
  38472. this._totalVertices = 0;
  38473. this._indices = [];
  38474. }
  38475. if (this._engine.getCaps().vertexArrayObject) {
  38476. this._vertexArrayObjects = {};
  38477. }
  38478. // applyToMesh
  38479. if (mesh) {
  38480. if (mesh.getClassName() === "LinesMesh") {
  38481. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38482. this._updateExtend();
  38483. }
  38484. this.applyToMesh(mesh);
  38485. mesh.computeWorldMatrix(true);
  38486. }
  38487. }
  38488. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38489. /**
  38490. * 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
  38491. */
  38492. get: function () {
  38493. return this._boundingBias;
  38494. },
  38495. /**
  38496. * 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
  38497. */
  38498. set: function (value) {
  38499. if (this._boundingBias && this._boundingBias.equals(value)) {
  38500. return;
  38501. }
  38502. this._boundingBias = value.clone();
  38503. this._updateBoundingInfo(true, null);
  38504. },
  38505. enumerable: true,
  38506. configurable: true
  38507. });
  38508. /**
  38509. * Static function used to attach a new empty geometry to a mesh
  38510. * @param mesh defines the mesh to attach the geometry to
  38511. * @returns the new {BABYLON.Geometry}
  38512. */
  38513. Geometry.CreateGeometryForMesh = function (mesh) {
  38514. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38515. geometry.applyToMesh(mesh);
  38516. return geometry;
  38517. };
  38518. Object.defineProperty(Geometry.prototype, "extend", {
  38519. /**
  38520. * Gets the current extend of the geometry
  38521. */
  38522. get: function () {
  38523. return this._extend;
  38524. },
  38525. enumerable: true,
  38526. configurable: true
  38527. });
  38528. /**
  38529. * Gets the hosting scene
  38530. * @returns the hosting {BABYLON.Scene}
  38531. */
  38532. Geometry.prototype.getScene = function () {
  38533. return this._scene;
  38534. };
  38535. /**
  38536. * Gets the hosting engine
  38537. * @returns the hosting {BABYLON.Engine}
  38538. */
  38539. Geometry.prototype.getEngine = function () {
  38540. return this._engine;
  38541. };
  38542. /**
  38543. * Defines if the geometry is ready to use
  38544. * @returns true if the geometry is ready to be used
  38545. */
  38546. Geometry.prototype.isReady = function () {
  38547. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38548. };
  38549. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38550. /**
  38551. * Gets a value indicating that the geometry should not be serialized
  38552. */
  38553. get: function () {
  38554. for (var index = 0; index < this._meshes.length; index++) {
  38555. if (!this._meshes[index].doNotSerialize) {
  38556. return false;
  38557. }
  38558. }
  38559. return true;
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. /** @hidden */
  38565. Geometry.prototype._rebuild = function () {
  38566. if (this._vertexArrayObjects) {
  38567. this._vertexArrayObjects = {};
  38568. }
  38569. // Index buffer
  38570. if (this._meshes.length !== 0 && this._indices) {
  38571. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38572. }
  38573. // Vertex buffers
  38574. for (var key in this._vertexBuffers) {
  38575. var vertexBuffer = this._vertexBuffers[key];
  38576. vertexBuffer._rebuild();
  38577. }
  38578. };
  38579. /**
  38580. * Affects all geometry data in one call
  38581. * @param vertexData defines the geometry data
  38582. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38583. */
  38584. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38585. vertexData.applyToGeometry(this, updatable);
  38586. this.notifyUpdate();
  38587. };
  38588. /**
  38589. * Set specific vertex data
  38590. * @param kind defines the data kind (Position, normal, etc...)
  38591. * @param data defines the vertex data to use
  38592. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38593. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38594. */
  38595. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38596. if (updatable === void 0) { updatable = false; }
  38597. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38598. this.setVerticesBuffer(buffer);
  38599. };
  38600. /**
  38601. * Removes a specific vertex data
  38602. * @param kind defines the data kind (Position, normal, etc...)
  38603. */
  38604. Geometry.prototype.removeVerticesData = function (kind) {
  38605. if (this._vertexBuffers[kind]) {
  38606. this._vertexBuffers[kind].dispose();
  38607. delete this._vertexBuffers[kind];
  38608. }
  38609. };
  38610. /**
  38611. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38612. * @param buffer defines the vertex buffer to use
  38613. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38614. */
  38615. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38616. if (totalVertices === void 0) { totalVertices = null; }
  38617. var kind = buffer.getKind();
  38618. if (this._vertexBuffers[kind]) {
  38619. this._vertexBuffers[kind].dispose();
  38620. }
  38621. this._vertexBuffers[kind] = buffer;
  38622. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38623. var data = buffer.getData();
  38624. if (totalVertices != null) {
  38625. this._totalVertices = totalVertices;
  38626. }
  38627. else {
  38628. if (data != null) {
  38629. this._totalVertices = data.length / (buffer.byteStride / 4);
  38630. }
  38631. }
  38632. this._updateExtend(data);
  38633. this._resetPointsArrayCache();
  38634. var meshes = this._meshes;
  38635. var numOfMeshes = meshes.length;
  38636. for (var index = 0; index < numOfMeshes; index++) {
  38637. var mesh = meshes[index];
  38638. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38639. mesh._createGlobalSubMesh(false);
  38640. mesh.computeWorldMatrix(true);
  38641. }
  38642. }
  38643. this.notifyUpdate(kind);
  38644. if (this._vertexArrayObjects) {
  38645. this._disposeVertexArrayObjects();
  38646. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38647. }
  38648. };
  38649. /**
  38650. * Update a specific vertex buffer
  38651. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38652. * It will do nothing if the buffer is not updatable
  38653. * @param kind defines the data kind (Position, normal, etc...)
  38654. * @param data defines the data to use
  38655. * @param offset defines the offset in the target buffer where to store the data
  38656. * @param useBytes set to true if the offset is in bytes
  38657. */
  38658. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38659. if (useBytes === void 0) { useBytes = false; }
  38660. var vertexBuffer = this.getVertexBuffer(kind);
  38661. if (!vertexBuffer) {
  38662. return;
  38663. }
  38664. vertexBuffer.updateDirectly(data, offset, useBytes);
  38665. this.notifyUpdate(kind);
  38666. };
  38667. /**
  38668. * Update a specific vertex buffer
  38669. * This function will create a new buffer if the current one is not updatable
  38670. * @param kind defines the data kind (Position, normal, etc...)
  38671. * @param data defines the data to use
  38672. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38673. */
  38674. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38675. if (updateExtends === void 0) { updateExtends = false; }
  38676. var vertexBuffer = this.getVertexBuffer(kind);
  38677. if (!vertexBuffer) {
  38678. return;
  38679. }
  38680. vertexBuffer.update(data);
  38681. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38682. this._updateBoundingInfo(updateExtends, data);
  38683. }
  38684. this.notifyUpdate(kind);
  38685. };
  38686. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38687. if (updateExtends) {
  38688. this._updateExtend(data);
  38689. }
  38690. var meshes = this._meshes;
  38691. var numOfMeshes = meshes.length;
  38692. this._resetPointsArrayCache();
  38693. for (var index = 0; index < numOfMeshes; index++) {
  38694. var mesh = meshes[index];
  38695. if (updateExtends) {
  38696. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38697. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38698. var subMesh = mesh.subMeshes[subIndex];
  38699. subMesh.refreshBoundingInfo();
  38700. }
  38701. }
  38702. }
  38703. };
  38704. /** @hidden */
  38705. Geometry.prototype._bind = function (effect, indexToBind) {
  38706. if (!effect) {
  38707. return;
  38708. }
  38709. if (indexToBind === undefined) {
  38710. indexToBind = this._indexBuffer;
  38711. }
  38712. var vbs = this.getVertexBuffers();
  38713. if (!vbs) {
  38714. return;
  38715. }
  38716. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38717. this._engine.bindBuffers(vbs, indexToBind, effect);
  38718. return;
  38719. }
  38720. // Using VAO
  38721. if (!this._vertexArrayObjects[effect.key]) {
  38722. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38723. }
  38724. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38725. };
  38726. /**
  38727. * Gets total number of vertices
  38728. * @returns the total number of vertices
  38729. */
  38730. Geometry.prototype.getTotalVertices = function () {
  38731. if (!this.isReady()) {
  38732. return 0;
  38733. }
  38734. return this._totalVertices;
  38735. };
  38736. /**
  38737. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38738. * @param kind defines the data kind (Position, normal, etc...)
  38739. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38740. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38741. * @returns a float array containing vertex data
  38742. */
  38743. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38744. var vertexBuffer = this.getVertexBuffer(kind);
  38745. if (!vertexBuffer) {
  38746. return null;
  38747. }
  38748. var data = vertexBuffer.getData();
  38749. if (!data) {
  38750. return null;
  38751. }
  38752. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38753. var count = this._totalVertices * vertexBuffer.getSize();
  38754. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38755. var copy_1 = new Array(count);
  38756. vertexBuffer.forEach(count, function (value, index) {
  38757. copy_1[index] = value;
  38758. });
  38759. return copy_1;
  38760. }
  38761. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38762. if (data instanceof Array) {
  38763. var offset = vertexBuffer.byteOffset / 4;
  38764. return BABYLON.Tools.Slice(data, offset, offset + count);
  38765. }
  38766. else if (data instanceof ArrayBuffer) {
  38767. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38768. }
  38769. else {
  38770. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38771. }
  38772. }
  38773. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38774. return BABYLON.Tools.Slice(data);
  38775. }
  38776. return data;
  38777. };
  38778. /**
  38779. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38780. * @param kind defines the data kind (Position, normal, etc...)
  38781. * @returns true if the vertex buffer with the specified kind is updatable
  38782. */
  38783. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38784. var vb = this._vertexBuffers[kind];
  38785. if (!vb) {
  38786. return false;
  38787. }
  38788. return vb.isUpdatable();
  38789. };
  38790. /**
  38791. * Gets a specific vertex buffer
  38792. * @param kind defines the data kind (Position, normal, etc...)
  38793. * @returns a {BABYLON.VertexBuffer}
  38794. */
  38795. Geometry.prototype.getVertexBuffer = function (kind) {
  38796. if (!this.isReady()) {
  38797. return null;
  38798. }
  38799. return this._vertexBuffers[kind];
  38800. };
  38801. /**
  38802. * Returns all vertex buffers
  38803. * @return an object holding all vertex buffers indexed by kind
  38804. */
  38805. Geometry.prototype.getVertexBuffers = function () {
  38806. if (!this.isReady()) {
  38807. return null;
  38808. }
  38809. return this._vertexBuffers;
  38810. };
  38811. /**
  38812. * Gets a boolean indicating if specific vertex buffer is present
  38813. * @param kind defines the data kind (Position, normal, etc...)
  38814. * @returns true if data is present
  38815. */
  38816. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38817. if (!this._vertexBuffers) {
  38818. if (this._delayInfo) {
  38819. return this._delayInfo.indexOf(kind) !== -1;
  38820. }
  38821. return false;
  38822. }
  38823. return this._vertexBuffers[kind] !== undefined;
  38824. };
  38825. /**
  38826. * Gets a list of all attached data kinds (Position, normal, etc...)
  38827. * @returns a list of string containing all kinds
  38828. */
  38829. Geometry.prototype.getVerticesDataKinds = function () {
  38830. var result = [];
  38831. var kind;
  38832. if (!this._vertexBuffers && this._delayInfo) {
  38833. for (kind in this._delayInfo) {
  38834. result.push(kind);
  38835. }
  38836. }
  38837. else {
  38838. for (kind in this._vertexBuffers) {
  38839. result.push(kind);
  38840. }
  38841. }
  38842. return result;
  38843. };
  38844. /**
  38845. * Update index buffer
  38846. * @param indices defines the indices to store in the index buffer
  38847. * @param offset defines the offset in the target buffer where to store the data
  38848. */
  38849. Geometry.prototype.updateIndices = function (indices, offset) {
  38850. if (!this._indexBuffer) {
  38851. return;
  38852. }
  38853. if (!this._indexBufferIsUpdatable) {
  38854. this.setIndices(indices, null, true);
  38855. }
  38856. else {
  38857. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38858. }
  38859. };
  38860. /**
  38861. * Creates a new index buffer
  38862. * @param indices defines the indices to store in the index buffer
  38863. * @param totalVertices defines the total number of vertices (could be null)
  38864. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38865. */
  38866. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38867. if (totalVertices === void 0) { totalVertices = null; }
  38868. if (updatable === void 0) { updatable = false; }
  38869. if (this._indexBuffer) {
  38870. this._engine._releaseBuffer(this._indexBuffer);
  38871. }
  38872. this._disposeVertexArrayObjects();
  38873. this._indices = indices;
  38874. this._indexBufferIsUpdatable = updatable;
  38875. if (this._meshes.length !== 0 && this._indices) {
  38876. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38877. }
  38878. if (totalVertices != undefined) { // including null and undefined
  38879. this._totalVertices = totalVertices;
  38880. }
  38881. var meshes = this._meshes;
  38882. var numOfMeshes = meshes.length;
  38883. for (var index = 0; index < numOfMeshes; index++) {
  38884. meshes[index]._createGlobalSubMesh(true);
  38885. }
  38886. this.notifyUpdate();
  38887. };
  38888. /**
  38889. * Return the total number of indices
  38890. * @returns the total number of indices
  38891. */
  38892. Geometry.prototype.getTotalIndices = function () {
  38893. if (!this.isReady()) {
  38894. return 0;
  38895. }
  38896. return this._indices.length;
  38897. };
  38898. /**
  38899. * Gets the index buffer array
  38900. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38901. * @returns the index buffer array
  38902. */
  38903. Geometry.prototype.getIndices = function (copyWhenShared) {
  38904. if (!this.isReady()) {
  38905. return null;
  38906. }
  38907. var orig = this._indices;
  38908. if (!copyWhenShared || this._meshes.length === 1) {
  38909. return orig;
  38910. }
  38911. else {
  38912. var len = orig.length;
  38913. var copy = [];
  38914. for (var i = 0; i < len; i++) {
  38915. copy.push(orig[i]);
  38916. }
  38917. return copy;
  38918. }
  38919. };
  38920. /**
  38921. * Gets the index buffer
  38922. * @return the index buffer
  38923. */
  38924. Geometry.prototype.getIndexBuffer = function () {
  38925. if (!this.isReady()) {
  38926. return null;
  38927. }
  38928. return this._indexBuffer;
  38929. };
  38930. /** @hidden */
  38931. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38932. if (effect === void 0) { effect = null; }
  38933. if (!effect || !this._vertexArrayObjects) {
  38934. return;
  38935. }
  38936. if (this._vertexArrayObjects[effect.key]) {
  38937. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38938. delete this._vertexArrayObjects[effect.key];
  38939. }
  38940. };
  38941. /**
  38942. * Release the associated resources for a specific mesh
  38943. * @param mesh defines the source mesh
  38944. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38945. */
  38946. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38947. var meshes = this._meshes;
  38948. var index = meshes.indexOf(mesh);
  38949. if (index === -1) {
  38950. return;
  38951. }
  38952. meshes.splice(index, 1);
  38953. mesh._geometry = null;
  38954. if (meshes.length === 0 && shouldDispose) {
  38955. this.dispose();
  38956. }
  38957. };
  38958. /**
  38959. * Apply current geometry to a given mesh
  38960. * @param mesh defines the mesh to apply geometry to
  38961. */
  38962. Geometry.prototype.applyToMesh = function (mesh) {
  38963. if (mesh._geometry === this) {
  38964. return;
  38965. }
  38966. var previousGeometry = mesh._geometry;
  38967. if (previousGeometry) {
  38968. previousGeometry.releaseForMesh(mesh);
  38969. }
  38970. var meshes = this._meshes;
  38971. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38972. mesh._geometry = this;
  38973. this._scene.pushGeometry(this);
  38974. meshes.push(mesh);
  38975. if (this.isReady()) {
  38976. this._applyToMesh(mesh);
  38977. }
  38978. else {
  38979. mesh._boundingInfo = this._boundingInfo;
  38980. }
  38981. };
  38982. Geometry.prototype._updateExtend = function (data) {
  38983. if (data === void 0) { data = null; }
  38984. if (!data) {
  38985. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38986. }
  38987. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38988. };
  38989. Geometry.prototype._applyToMesh = function (mesh) {
  38990. var numOfMeshes = this._meshes.length;
  38991. // vertexBuffers
  38992. for (var kind in this._vertexBuffers) {
  38993. if (numOfMeshes === 1) {
  38994. this._vertexBuffers[kind].create();
  38995. }
  38996. var buffer = this._vertexBuffers[kind].getBuffer();
  38997. if (buffer)
  38998. buffer.references = numOfMeshes;
  38999. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39000. if (!this._extend) {
  39001. this._updateExtend();
  39002. }
  39003. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39004. mesh._createGlobalSubMesh(false);
  39005. //bounding info was just created again, world matrix should be applied again.
  39006. mesh._updateBoundingInfo();
  39007. }
  39008. }
  39009. // indexBuffer
  39010. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39011. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39012. }
  39013. if (this._indexBuffer) {
  39014. this._indexBuffer.references = numOfMeshes;
  39015. }
  39016. };
  39017. Geometry.prototype.notifyUpdate = function (kind) {
  39018. if (this.onGeometryUpdated) {
  39019. this.onGeometryUpdated(this, kind);
  39020. }
  39021. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39022. var mesh = _a[_i];
  39023. mesh._markSubMeshesAsAttributesDirty();
  39024. }
  39025. };
  39026. /**
  39027. * Load the geometry if it was flagged as delay loaded
  39028. * @param scene defines the hosting scene
  39029. * @param onLoaded defines a callback called when the geometry is loaded
  39030. */
  39031. Geometry.prototype.load = function (scene, onLoaded) {
  39032. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39033. return;
  39034. }
  39035. if (this.isReady()) {
  39036. if (onLoaded) {
  39037. onLoaded();
  39038. }
  39039. return;
  39040. }
  39041. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39042. this._queueLoad(scene, onLoaded);
  39043. };
  39044. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39045. var _this = this;
  39046. if (!this.delayLoadingFile) {
  39047. return;
  39048. }
  39049. scene._addPendingData(this);
  39050. scene._loadFile(this.delayLoadingFile, function (data) {
  39051. if (!_this._delayLoadingFunction) {
  39052. return;
  39053. }
  39054. _this._delayLoadingFunction(JSON.parse(data), _this);
  39055. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39056. _this._delayInfo = [];
  39057. scene._removePendingData(_this);
  39058. var meshes = _this._meshes;
  39059. var numOfMeshes = meshes.length;
  39060. for (var index = 0; index < numOfMeshes; index++) {
  39061. _this._applyToMesh(meshes[index]);
  39062. }
  39063. if (onLoaded) {
  39064. onLoaded();
  39065. }
  39066. }, undefined, true);
  39067. };
  39068. /**
  39069. * Invert the geometry to move from a right handed system to a left handed one.
  39070. */
  39071. Geometry.prototype.toLeftHanded = function () {
  39072. // Flip faces
  39073. var tIndices = this.getIndices(false);
  39074. if (tIndices != null && tIndices.length > 0) {
  39075. for (var i = 0; i < tIndices.length; i += 3) {
  39076. var tTemp = tIndices[i + 0];
  39077. tIndices[i + 0] = tIndices[i + 2];
  39078. tIndices[i + 2] = tTemp;
  39079. }
  39080. this.setIndices(tIndices);
  39081. }
  39082. // Negate position.z
  39083. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39084. if (tPositions != null && tPositions.length > 0) {
  39085. for (var i = 0; i < tPositions.length; i += 3) {
  39086. tPositions[i + 2] = -tPositions[i + 2];
  39087. }
  39088. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39089. }
  39090. // Negate normal.z
  39091. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39092. if (tNormals != null && tNormals.length > 0) {
  39093. for (var i = 0; i < tNormals.length; i += 3) {
  39094. tNormals[i + 2] = -tNormals[i + 2];
  39095. }
  39096. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39097. }
  39098. };
  39099. // Cache
  39100. /** @hidden */
  39101. Geometry.prototype._resetPointsArrayCache = function () {
  39102. this._positions = null;
  39103. };
  39104. /** @hidden */
  39105. Geometry.prototype._generatePointsArray = function () {
  39106. if (this._positions)
  39107. return true;
  39108. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39109. if (!data || data.length === 0) {
  39110. return false;
  39111. }
  39112. this._positions = [];
  39113. for (var index = 0; index < data.length; index += 3) {
  39114. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39115. }
  39116. return true;
  39117. };
  39118. /**
  39119. * Gets a value indicating if the geometry is disposed
  39120. * @returns true if the geometry was disposed
  39121. */
  39122. Geometry.prototype.isDisposed = function () {
  39123. return this._isDisposed;
  39124. };
  39125. Geometry.prototype._disposeVertexArrayObjects = function () {
  39126. if (this._vertexArrayObjects) {
  39127. for (var kind in this._vertexArrayObjects) {
  39128. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39129. }
  39130. this._vertexArrayObjects = {};
  39131. }
  39132. };
  39133. /**
  39134. * Free all associated resources
  39135. */
  39136. Geometry.prototype.dispose = function () {
  39137. var meshes = this._meshes;
  39138. var numOfMeshes = meshes.length;
  39139. var index;
  39140. for (index = 0; index < numOfMeshes; index++) {
  39141. this.releaseForMesh(meshes[index]);
  39142. }
  39143. this._meshes = [];
  39144. this._disposeVertexArrayObjects();
  39145. for (var kind in this._vertexBuffers) {
  39146. this._vertexBuffers[kind].dispose();
  39147. }
  39148. this._vertexBuffers = {};
  39149. this._totalVertices = 0;
  39150. if (this._indexBuffer) {
  39151. this._engine._releaseBuffer(this._indexBuffer);
  39152. }
  39153. this._indexBuffer = null;
  39154. this._indices = [];
  39155. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39156. this.delayLoadingFile = null;
  39157. this._delayLoadingFunction = null;
  39158. this._delayInfo = [];
  39159. this._boundingInfo = null;
  39160. this._scene.removeGeometry(this);
  39161. this._isDisposed = true;
  39162. };
  39163. /**
  39164. * Clone the current geometry into a new geometry
  39165. * @param id defines the unique ID of the new geometry
  39166. * @returns a new geometry object
  39167. */
  39168. Geometry.prototype.copy = function (id) {
  39169. var vertexData = new BABYLON.VertexData();
  39170. vertexData.indices = [];
  39171. var indices = this.getIndices();
  39172. if (indices) {
  39173. for (var index = 0; index < indices.length; index++) {
  39174. vertexData.indices.push(indices[index]);
  39175. }
  39176. }
  39177. var updatable = false;
  39178. var stopChecking = false;
  39179. var kind;
  39180. for (kind in this._vertexBuffers) {
  39181. // using slice() to make a copy of the array and not just reference it
  39182. var data = this.getVerticesData(kind);
  39183. if (data instanceof Float32Array) {
  39184. vertexData.set(new Float32Array(data), kind);
  39185. }
  39186. else {
  39187. vertexData.set(data.slice(0), kind);
  39188. }
  39189. if (!stopChecking) {
  39190. var vb = this.getVertexBuffer(kind);
  39191. if (vb) {
  39192. updatable = vb.isUpdatable();
  39193. stopChecking = !updatable;
  39194. }
  39195. }
  39196. }
  39197. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39198. geometry.delayLoadState = this.delayLoadState;
  39199. geometry.delayLoadingFile = this.delayLoadingFile;
  39200. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39201. for (kind in this._delayInfo) {
  39202. geometry._delayInfo = geometry._delayInfo || [];
  39203. geometry._delayInfo.push(kind);
  39204. }
  39205. // Bounding info
  39206. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39207. return geometry;
  39208. };
  39209. /**
  39210. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39211. * @return a JSON representation of the current geometry data (without the vertices data)
  39212. */
  39213. Geometry.prototype.serialize = function () {
  39214. var serializationObject = {};
  39215. serializationObject.id = this.id;
  39216. serializationObject.updatable = this._updatable;
  39217. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39218. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39219. }
  39220. return serializationObject;
  39221. };
  39222. Geometry.prototype.toNumberArray = function (origin) {
  39223. if (Array.isArray(origin)) {
  39224. return origin;
  39225. }
  39226. else {
  39227. return Array.prototype.slice.call(origin);
  39228. }
  39229. };
  39230. /**
  39231. * Serialize all vertices data into a JSON oject
  39232. * @returns a JSON representation of the current geometry data
  39233. */
  39234. Geometry.prototype.serializeVerticeData = function () {
  39235. var serializationObject = this.serialize();
  39236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39237. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39239. serializationObject.positions._updatable = true;
  39240. }
  39241. }
  39242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39243. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39244. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39245. serializationObject.normals._updatable = true;
  39246. }
  39247. }
  39248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39249. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39250. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39251. serializationObject.tangets._updatable = true;
  39252. }
  39253. }
  39254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39255. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39256. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39257. serializationObject.uvs._updatable = true;
  39258. }
  39259. }
  39260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39261. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39262. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39263. serializationObject.uv2s._updatable = true;
  39264. }
  39265. }
  39266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39267. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39268. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39269. serializationObject.uv3s._updatable = true;
  39270. }
  39271. }
  39272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39273. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39274. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39275. serializationObject.uv4s._updatable = true;
  39276. }
  39277. }
  39278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39279. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39280. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39281. serializationObject.uv5s._updatable = true;
  39282. }
  39283. }
  39284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39285. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39286. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39287. serializationObject.uv6s._updatable = true;
  39288. }
  39289. }
  39290. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39291. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39292. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39293. serializationObject.colors._updatable = true;
  39294. }
  39295. }
  39296. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39297. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39298. serializationObject.matricesIndices._isExpanded = true;
  39299. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39300. serializationObject.matricesIndices._updatable = true;
  39301. }
  39302. }
  39303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39304. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39305. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39306. serializationObject.matricesWeights._updatable = true;
  39307. }
  39308. }
  39309. serializationObject.indices = this.toNumberArray(this.getIndices());
  39310. return serializationObject;
  39311. };
  39312. // Statics
  39313. /**
  39314. * Extracts a clone of a mesh geometry
  39315. * @param mesh defines the source mesh
  39316. * @param id defines the unique ID of the new geometry object
  39317. * @returns the new geometry object
  39318. */
  39319. Geometry.ExtractFromMesh = function (mesh, id) {
  39320. var geometry = mesh._geometry;
  39321. if (!geometry) {
  39322. return null;
  39323. }
  39324. return geometry.copy(id);
  39325. };
  39326. /**
  39327. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39328. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39329. * Be aware Math.random() could cause collisions, but:
  39330. * "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"
  39331. * @returns a string containing a new GUID
  39332. */
  39333. Geometry.RandomId = function () {
  39334. return BABYLON.Tools.RandomId();
  39335. };
  39336. /** @hidden */
  39337. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39338. var scene = mesh.getScene();
  39339. // Geometry
  39340. var geometryId = parsedGeometry.geometryId;
  39341. if (geometryId) {
  39342. var geometry = scene.getGeometryByID(geometryId);
  39343. if (geometry) {
  39344. geometry.applyToMesh(mesh);
  39345. }
  39346. }
  39347. else if (parsedGeometry instanceof ArrayBuffer) {
  39348. var binaryInfo = mesh._binaryInfo;
  39349. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39350. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39351. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39352. }
  39353. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39354. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39355. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39356. }
  39357. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39358. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39359. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39360. }
  39361. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39362. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39363. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39364. }
  39365. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39366. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39367. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39368. }
  39369. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39370. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39371. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39372. }
  39373. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39374. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39375. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39376. }
  39377. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39378. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39379. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39380. }
  39381. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39382. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39383. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39384. }
  39385. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39386. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39387. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39388. }
  39389. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39390. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39391. var floatIndices = [];
  39392. for (var i = 0; i < matricesIndicesData.length; i++) {
  39393. var index = matricesIndicesData[i];
  39394. floatIndices.push(index & 0x000000FF);
  39395. floatIndices.push((index & 0x0000FF00) >> 8);
  39396. floatIndices.push((index & 0x00FF0000) >> 16);
  39397. floatIndices.push(index >> 24);
  39398. }
  39399. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39400. }
  39401. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39402. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39404. }
  39405. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39406. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39407. mesh.setIndices(indicesData, null);
  39408. }
  39409. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39410. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39411. mesh.subMeshes = [];
  39412. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39413. var materialIndex = subMeshesData[(i * 5) + 0];
  39414. var verticesStart = subMeshesData[(i * 5) + 1];
  39415. var verticesCount = subMeshesData[(i * 5) + 2];
  39416. var indexStart = subMeshesData[(i * 5) + 3];
  39417. var indexCount = subMeshesData[(i * 5) + 4];
  39418. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39419. }
  39420. }
  39421. }
  39422. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39423. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39424. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39425. if (parsedGeometry.tangents) {
  39426. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39427. }
  39428. if (parsedGeometry.uvs) {
  39429. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39430. }
  39431. if (parsedGeometry.uvs2) {
  39432. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39433. }
  39434. if (parsedGeometry.uvs3) {
  39435. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39436. }
  39437. if (parsedGeometry.uvs4) {
  39438. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39439. }
  39440. if (parsedGeometry.uvs5) {
  39441. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39442. }
  39443. if (parsedGeometry.uvs6) {
  39444. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39445. }
  39446. if (parsedGeometry.colors) {
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39448. }
  39449. if (parsedGeometry.matricesIndices) {
  39450. if (!parsedGeometry.matricesIndices._isExpanded) {
  39451. var floatIndices = [];
  39452. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39453. var matricesIndex = parsedGeometry.matricesIndices[i];
  39454. floatIndices.push(matricesIndex & 0x000000FF);
  39455. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39456. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39457. floatIndices.push(matricesIndex >> 24);
  39458. }
  39459. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39460. }
  39461. else {
  39462. delete parsedGeometry.matricesIndices._isExpanded;
  39463. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39464. }
  39465. }
  39466. if (parsedGeometry.matricesIndicesExtra) {
  39467. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39468. var floatIndices = [];
  39469. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39470. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39471. floatIndices.push(matricesIndex & 0x000000FF);
  39472. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39473. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39474. floatIndices.push(matricesIndex >> 24);
  39475. }
  39476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39477. }
  39478. else {
  39479. delete parsedGeometry.matricesIndices._isExpanded;
  39480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39481. }
  39482. }
  39483. if (parsedGeometry.matricesWeights) {
  39484. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39485. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39486. }
  39487. if (parsedGeometry.matricesWeightsExtra) {
  39488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39489. }
  39490. mesh.setIndices(parsedGeometry.indices, null);
  39491. }
  39492. // SubMeshes
  39493. if (parsedGeometry.subMeshes) {
  39494. mesh.subMeshes = [];
  39495. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39496. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39497. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39498. }
  39499. }
  39500. // Flat shading
  39501. if (mesh._shouldGenerateFlatShading) {
  39502. mesh.convertToFlatShadedMesh();
  39503. delete mesh._shouldGenerateFlatShading;
  39504. }
  39505. // Update
  39506. mesh.computeWorldMatrix(true);
  39507. // Octree
  39508. var sceneOctree = scene.selectionOctree;
  39509. if (sceneOctree !== undefined && sceneOctree !== null) {
  39510. sceneOctree.addMesh(mesh);
  39511. }
  39512. };
  39513. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39514. var epsilon = 1e-3;
  39515. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39516. return;
  39517. }
  39518. var noInfluenceBoneIndex = 0.0;
  39519. if (parsedGeometry.skeletonId > -1) {
  39520. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39521. if (!skeleton) {
  39522. return;
  39523. }
  39524. noInfluenceBoneIndex = skeleton.bones.length;
  39525. }
  39526. else {
  39527. return;
  39528. }
  39529. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39530. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39531. var matricesWeights = parsedGeometry.matricesWeights;
  39532. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39533. var influencers = parsedGeometry.numBoneInfluencer;
  39534. var size = matricesWeights.length;
  39535. for (var i = 0; i < size; i += 4) {
  39536. var weight = 0.0;
  39537. var firstZeroWeight = -1;
  39538. for (var j = 0; j < 4; j++) {
  39539. var w = matricesWeights[i + j];
  39540. weight += w;
  39541. if (w < epsilon && firstZeroWeight < 0) {
  39542. firstZeroWeight = j;
  39543. }
  39544. }
  39545. if (matricesWeightsExtra) {
  39546. for (var j = 0; j < 4; j++) {
  39547. var w = matricesWeightsExtra[i + j];
  39548. weight += w;
  39549. if (w < epsilon && firstZeroWeight < 0) {
  39550. firstZeroWeight = j + 4;
  39551. }
  39552. }
  39553. }
  39554. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39555. firstZeroWeight = influencers - 1;
  39556. }
  39557. if (weight > epsilon) {
  39558. var mweight = 1.0 / weight;
  39559. for (var j = 0; j < 4; j++) {
  39560. matricesWeights[i + j] *= mweight;
  39561. }
  39562. if (matricesWeightsExtra) {
  39563. for (var j = 0; j < 4; j++) {
  39564. matricesWeightsExtra[i + j] *= mweight;
  39565. }
  39566. }
  39567. }
  39568. else {
  39569. if (firstZeroWeight >= 4) {
  39570. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39571. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39572. }
  39573. else {
  39574. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39575. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39576. }
  39577. }
  39578. }
  39579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39580. if (parsedGeometry.matricesWeightsExtra) {
  39581. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39582. }
  39583. };
  39584. /**
  39585. * Create a new geometry from persisted data (Using .babylon file format)
  39586. * @param parsedVertexData defines the persisted data
  39587. * @param scene defines the hosting scene
  39588. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39589. * @returns the new geometry object
  39590. */
  39591. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39592. if (scene.getGeometryByID(parsedVertexData.id)) {
  39593. return null; // null since geometry could be something else than a box...
  39594. }
  39595. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39596. if (BABYLON.Tags) {
  39597. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39598. }
  39599. if (parsedVertexData.delayLoadingFile) {
  39600. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39601. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39602. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39603. geometry._delayInfo = [];
  39604. if (parsedVertexData.hasUVs) {
  39605. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39606. }
  39607. if (parsedVertexData.hasUVs2) {
  39608. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39609. }
  39610. if (parsedVertexData.hasUVs3) {
  39611. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39612. }
  39613. if (parsedVertexData.hasUVs4) {
  39614. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39615. }
  39616. if (parsedVertexData.hasUVs5) {
  39617. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39618. }
  39619. if (parsedVertexData.hasUVs6) {
  39620. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39621. }
  39622. if (parsedVertexData.hasColors) {
  39623. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39624. }
  39625. if (parsedVertexData.hasMatricesIndices) {
  39626. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39627. }
  39628. if (parsedVertexData.hasMatricesWeights) {
  39629. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39630. }
  39631. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39632. }
  39633. else {
  39634. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39635. }
  39636. scene.pushGeometry(geometry, true);
  39637. return geometry;
  39638. };
  39639. return Geometry;
  39640. }());
  39641. BABYLON.Geometry = Geometry;
  39642. // Primitives
  39643. /// Abstract class
  39644. /**
  39645. * Abstract class used to provide common services for all typed geometries
  39646. * @hidden
  39647. */
  39648. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39649. __extends(_PrimitiveGeometry, _super);
  39650. /**
  39651. * Creates a new typed geometry
  39652. * @param id defines the unique ID of the geometry
  39653. * @param scene defines the hosting scene
  39654. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39655. * @param mesh defines the hosting mesh (can be null)
  39656. */
  39657. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39658. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39659. if (mesh === void 0) { mesh = null; }
  39660. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39661. _this._canBeRegenerated = _canBeRegenerated;
  39662. _this._beingRegenerated = true;
  39663. _this.regenerate();
  39664. _this._beingRegenerated = false;
  39665. return _this;
  39666. }
  39667. /**
  39668. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39669. * @returns true if the geometry can be regenerated
  39670. */
  39671. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39672. return this._canBeRegenerated;
  39673. };
  39674. /**
  39675. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39676. */
  39677. _PrimitiveGeometry.prototype.regenerate = function () {
  39678. if (!this._canBeRegenerated) {
  39679. return;
  39680. }
  39681. this._beingRegenerated = true;
  39682. this.setAllVerticesData(this._regenerateVertexData(), false);
  39683. this._beingRegenerated = false;
  39684. };
  39685. /**
  39686. * Clone the geometry
  39687. * @param id defines the unique ID of the new geometry
  39688. * @returns the new geometry
  39689. */
  39690. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39691. return _super.prototype.copy.call(this, id);
  39692. };
  39693. // overrides
  39694. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39695. if (!this._beingRegenerated) {
  39696. return;
  39697. }
  39698. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39699. };
  39700. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39701. if (!this._beingRegenerated) {
  39702. return;
  39703. }
  39704. _super.prototype.setVerticesData.call(this, kind, data, false);
  39705. };
  39706. // to override
  39707. /** @hidden */
  39708. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39709. throw new Error("Abstract method");
  39710. };
  39711. _PrimitiveGeometry.prototype.copy = function (id) {
  39712. throw new Error("Must be overriden in sub-classes.");
  39713. };
  39714. _PrimitiveGeometry.prototype.serialize = function () {
  39715. var serializationObject = _super.prototype.serialize.call(this);
  39716. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39717. return serializationObject;
  39718. };
  39719. return _PrimitiveGeometry;
  39720. }(Geometry));
  39721. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39722. /**
  39723. * Creates a ribbon geometry
  39724. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39725. */
  39726. var RibbonGeometry = /** @class */ (function (_super) {
  39727. __extends(RibbonGeometry, _super);
  39728. /**
  39729. * Creates a ribbon geometry
  39730. * @param id defines the unique ID of the geometry
  39731. * @param scene defines the hosting scene
  39732. * @param pathArray defines the array of paths to use
  39733. * @param closeArray defines if the last path and the first path must be joined
  39734. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39735. * @param offset defines the offset between points
  39736. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39737. * @param mesh defines the hosting mesh (can be null)
  39738. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39739. */
  39740. function RibbonGeometry(id, scene,
  39741. /**
  39742. * Defines the array of paths to use
  39743. */
  39744. pathArray,
  39745. /**
  39746. * Defines if the last and first points of each path in your pathArray must be joined
  39747. */
  39748. closeArray,
  39749. /**
  39750. * Defines if the last and first points of each path in your pathArray must be joined
  39751. */
  39752. closePath,
  39753. /**
  39754. * Defines the offset between points
  39755. */
  39756. offset, canBeRegenerated, mesh,
  39757. /**
  39758. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39759. */
  39760. side) {
  39761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39763. _this.pathArray = pathArray;
  39764. _this.closeArray = closeArray;
  39765. _this.closePath = closePath;
  39766. _this.offset = offset;
  39767. _this.side = side;
  39768. return _this;
  39769. }
  39770. /** @hidden */
  39771. RibbonGeometry.prototype._regenerateVertexData = function () {
  39772. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39773. };
  39774. RibbonGeometry.prototype.copy = function (id) {
  39775. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39776. };
  39777. return RibbonGeometry;
  39778. }(_PrimitiveGeometry));
  39779. BABYLON.RibbonGeometry = RibbonGeometry;
  39780. /**
  39781. * Creates a box geometry
  39782. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39783. */
  39784. var BoxGeometry = /** @class */ (function (_super) {
  39785. __extends(BoxGeometry, _super);
  39786. /**
  39787. * Creates a box geometry
  39788. * @param id defines the unique ID of the geometry
  39789. * @param scene defines the hosting scene
  39790. * @param size defines the zise of the box (width, height and depth are the same)
  39791. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39792. * @param mesh defines the hosting mesh (can be null)
  39793. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39794. */
  39795. function BoxGeometry(id, scene,
  39796. /**
  39797. * Defines the zise of the box (width, height and depth are the same)
  39798. */
  39799. size, canBeRegenerated, mesh,
  39800. /**
  39801. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39802. */
  39803. side) {
  39804. if (mesh === void 0) { mesh = null; }
  39805. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39806. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39807. _this.size = size;
  39808. _this.side = side;
  39809. return _this;
  39810. }
  39811. BoxGeometry.prototype._regenerateVertexData = function () {
  39812. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39813. };
  39814. BoxGeometry.prototype.copy = function (id) {
  39815. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39816. };
  39817. BoxGeometry.prototype.serialize = function () {
  39818. var serializationObject = _super.prototype.serialize.call(this);
  39819. serializationObject.size = this.size;
  39820. return serializationObject;
  39821. };
  39822. BoxGeometry.Parse = function (parsedBox, scene) {
  39823. if (scene.getGeometryByID(parsedBox.id)) {
  39824. return null; // null since geometry could be something else than a box...
  39825. }
  39826. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39827. if (BABYLON.Tags) {
  39828. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39829. }
  39830. scene.pushGeometry(box, true);
  39831. return box;
  39832. };
  39833. return BoxGeometry;
  39834. }(_PrimitiveGeometry));
  39835. BABYLON.BoxGeometry = BoxGeometry;
  39836. /**
  39837. * Creates a sphere geometry
  39838. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39839. */
  39840. var SphereGeometry = /** @class */ (function (_super) {
  39841. __extends(SphereGeometry, _super);
  39842. /**
  39843. * Create a new sphere geometry
  39844. * @param id defines the unique ID of the geometry
  39845. * @param scene defines the hosting scene
  39846. * @param segments defines the number of segments to use to create the sphere
  39847. * @param diameter defines the diameter of the sphere
  39848. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39849. * @param mesh defines the hosting mesh (can be null)
  39850. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39851. */
  39852. function SphereGeometry(id, scene,
  39853. /**
  39854. * Defines the number of segments to use to create the sphere
  39855. */
  39856. segments,
  39857. /**
  39858. * Defines the diameter of the sphere
  39859. */
  39860. diameter, canBeRegenerated, mesh,
  39861. /**
  39862. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39863. */
  39864. side) {
  39865. if (mesh === void 0) { mesh = null; }
  39866. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39867. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39868. _this.segments = segments;
  39869. _this.diameter = diameter;
  39870. _this.side = side;
  39871. return _this;
  39872. }
  39873. SphereGeometry.prototype._regenerateVertexData = function () {
  39874. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39875. };
  39876. SphereGeometry.prototype.copy = function (id) {
  39877. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39878. };
  39879. SphereGeometry.prototype.serialize = function () {
  39880. var serializationObject = _super.prototype.serialize.call(this);
  39881. serializationObject.segments = this.segments;
  39882. serializationObject.diameter = this.diameter;
  39883. return serializationObject;
  39884. };
  39885. SphereGeometry.Parse = function (parsedSphere, scene) {
  39886. if (scene.getGeometryByID(parsedSphere.id)) {
  39887. return null; // null since geometry could be something else than a sphere...
  39888. }
  39889. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39890. if (BABYLON.Tags) {
  39891. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39892. }
  39893. scene.pushGeometry(sphere, true);
  39894. return sphere;
  39895. };
  39896. return SphereGeometry;
  39897. }(_PrimitiveGeometry));
  39898. BABYLON.SphereGeometry = SphereGeometry;
  39899. /**
  39900. * Creates a disc geometry
  39901. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39902. */
  39903. var DiscGeometry = /** @class */ (function (_super) {
  39904. __extends(DiscGeometry, _super);
  39905. /**
  39906. * Creates a new disc geometry
  39907. * @param id defines the unique ID of the geometry
  39908. * @param scene defines the hosting scene
  39909. * @param radius defines the radius of the disc
  39910. * @param tessellation defines the tesselation factor to apply to the disc
  39911. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39912. * @param mesh defines the hosting mesh (can be null)
  39913. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39914. */
  39915. function DiscGeometry(id, scene,
  39916. /**
  39917. * Defines the radius of the disc
  39918. */
  39919. radius,
  39920. /**
  39921. * Defines the tesselation factor to apply to the disc
  39922. */
  39923. tessellation, canBeRegenerated, mesh,
  39924. /**
  39925. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39926. */
  39927. side) {
  39928. if (mesh === void 0) { mesh = null; }
  39929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39931. _this.radius = radius;
  39932. _this.tessellation = tessellation;
  39933. _this.side = side;
  39934. return _this;
  39935. }
  39936. DiscGeometry.prototype._regenerateVertexData = function () {
  39937. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39938. };
  39939. DiscGeometry.prototype.copy = function (id) {
  39940. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39941. };
  39942. return DiscGeometry;
  39943. }(_PrimitiveGeometry));
  39944. BABYLON.DiscGeometry = DiscGeometry;
  39945. /**
  39946. * Creates a new cylinder geometry
  39947. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39948. */
  39949. var CylinderGeometry = /** @class */ (function (_super) {
  39950. __extends(CylinderGeometry, _super);
  39951. /**
  39952. * Creates a new cylinder geometry
  39953. * @param id defines the unique ID of the geometry
  39954. * @param scene defines the hosting scene
  39955. * @param height defines the height of the cylinder
  39956. * @param diameterTop defines the diameter of the cylinder's top cap
  39957. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39958. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39959. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39961. * @param mesh defines the hosting mesh (can be null)
  39962. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39963. */
  39964. function CylinderGeometry(id, scene,
  39965. /**
  39966. * Defines the height of the cylinder
  39967. */
  39968. height,
  39969. /**
  39970. * Defines the diameter of the cylinder's top cap
  39971. */
  39972. diameterTop,
  39973. /**
  39974. * Defines the diameter of the cylinder's bottom cap
  39975. */
  39976. diameterBottom,
  39977. /**
  39978. * Defines the tessellation factor to apply to the cylinder
  39979. */
  39980. tessellation,
  39981. /**
  39982. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39983. */
  39984. subdivisions, canBeRegenerated, mesh,
  39985. /**
  39986. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39987. */
  39988. side) {
  39989. if (subdivisions === void 0) { subdivisions = 1; }
  39990. if (mesh === void 0) { mesh = null; }
  39991. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39992. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39993. _this.height = height;
  39994. _this.diameterTop = diameterTop;
  39995. _this.diameterBottom = diameterBottom;
  39996. _this.tessellation = tessellation;
  39997. _this.subdivisions = subdivisions;
  39998. _this.side = side;
  39999. return _this;
  40000. }
  40001. CylinderGeometry.prototype._regenerateVertexData = function () {
  40002. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40003. };
  40004. CylinderGeometry.prototype.copy = function (id) {
  40005. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40006. };
  40007. CylinderGeometry.prototype.serialize = function () {
  40008. var serializationObject = _super.prototype.serialize.call(this);
  40009. serializationObject.height = this.height;
  40010. serializationObject.diameterTop = this.diameterTop;
  40011. serializationObject.diameterBottom = this.diameterBottom;
  40012. serializationObject.tessellation = this.tessellation;
  40013. return serializationObject;
  40014. };
  40015. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40016. if (scene.getGeometryByID(parsedCylinder.id)) {
  40017. return null; // null since geometry could be something else than a cylinder...
  40018. }
  40019. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40020. if (BABYLON.Tags) {
  40021. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40022. }
  40023. scene.pushGeometry(cylinder, true);
  40024. return cylinder;
  40025. };
  40026. return CylinderGeometry;
  40027. }(_PrimitiveGeometry));
  40028. BABYLON.CylinderGeometry = CylinderGeometry;
  40029. /**
  40030. * Creates a new torus geometry
  40031. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40032. */
  40033. var TorusGeometry = /** @class */ (function (_super) {
  40034. __extends(TorusGeometry, _super);
  40035. /**
  40036. * Creates a new torus geometry
  40037. * @param id defines the unique ID of the geometry
  40038. * @param scene defines the hosting scene
  40039. * @param diameter defines the diameter of the torus
  40040. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40041. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40042. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40043. * @param mesh defines the hosting mesh (can be null)
  40044. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40045. */
  40046. function TorusGeometry(id, scene,
  40047. /**
  40048. * Defines the diameter of the torus
  40049. */
  40050. diameter,
  40051. /**
  40052. * Defines the thickness of the torus (ie. internal diameter)
  40053. */
  40054. thickness,
  40055. /**
  40056. * Defines the tesselation factor to apply to the torus
  40057. */
  40058. tessellation, canBeRegenerated, mesh,
  40059. /**
  40060. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40061. */
  40062. side) {
  40063. if (mesh === void 0) { mesh = null; }
  40064. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40065. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40066. _this.diameter = diameter;
  40067. _this.thickness = thickness;
  40068. _this.tessellation = tessellation;
  40069. _this.side = side;
  40070. return _this;
  40071. }
  40072. TorusGeometry.prototype._regenerateVertexData = function () {
  40073. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40074. };
  40075. TorusGeometry.prototype.copy = function (id) {
  40076. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40077. };
  40078. TorusGeometry.prototype.serialize = function () {
  40079. var serializationObject = _super.prototype.serialize.call(this);
  40080. serializationObject.diameter = this.diameter;
  40081. serializationObject.thickness = this.thickness;
  40082. serializationObject.tessellation = this.tessellation;
  40083. return serializationObject;
  40084. };
  40085. TorusGeometry.Parse = function (parsedTorus, scene) {
  40086. if (scene.getGeometryByID(parsedTorus.id)) {
  40087. return null; // null since geometry could be something else than a torus...
  40088. }
  40089. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40090. if (BABYLON.Tags) {
  40091. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40092. }
  40093. scene.pushGeometry(torus, true);
  40094. return torus;
  40095. };
  40096. return TorusGeometry;
  40097. }(_PrimitiveGeometry));
  40098. BABYLON.TorusGeometry = TorusGeometry;
  40099. /**
  40100. * Creates a new ground geometry
  40101. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40102. */
  40103. var GroundGeometry = /** @class */ (function (_super) {
  40104. __extends(GroundGeometry, _super);
  40105. /**
  40106. * Creates a new ground geometry
  40107. * @param id defines the unique ID of the geometry
  40108. * @param scene defines the hosting scene
  40109. * @param width defines the width of the ground
  40110. * @param height defines the height of the ground
  40111. * @param subdivisions defines the subdivisions to apply to the ground
  40112. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40113. * @param mesh defines the hosting mesh (can be null)
  40114. */
  40115. function GroundGeometry(id, scene,
  40116. /**
  40117. * Defines the width of the ground
  40118. */
  40119. width,
  40120. /**
  40121. * Defines the height of the ground
  40122. */
  40123. height,
  40124. /**
  40125. * Defines the subdivisions to apply to the ground
  40126. */
  40127. subdivisions, canBeRegenerated, mesh) {
  40128. if (mesh === void 0) { mesh = null; }
  40129. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40130. _this.width = width;
  40131. _this.height = height;
  40132. _this.subdivisions = subdivisions;
  40133. return _this;
  40134. }
  40135. GroundGeometry.prototype._regenerateVertexData = function () {
  40136. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40137. };
  40138. GroundGeometry.prototype.copy = function (id) {
  40139. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40140. };
  40141. GroundGeometry.prototype.serialize = function () {
  40142. var serializationObject = _super.prototype.serialize.call(this);
  40143. serializationObject.width = this.width;
  40144. serializationObject.height = this.height;
  40145. serializationObject.subdivisions = this.subdivisions;
  40146. return serializationObject;
  40147. };
  40148. GroundGeometry.Parse = function (parsedGround, scene) {
  40149. if (scene.getGeometryByID(parsedGround.id)) {
  40150. return null; // null since geometry could be something else than a ground...
  40151. }
  40152. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40153. if (BABYLON.Tags) {
  40154. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40155. }
  40156. scene.pushGeometry(ground, true);
  40157. return ground;
  40158. };
  40159. return GroundGeometry;
  40160. }(_PrimitiveGeometry));
  40161. BABYLON.GroundGeometry = GroundGeometry;
  40162. /**
  40163. * Creates a tiled ground geometry
  40164. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40165. */
  40166. var TiledGroundGeometry = /** @class */ (function (_super) {
  40167. __extends(TiledGroundGeometry, _super);
  40168. /**
  40169. * Creates a tiled ground geometry
  40170. * @param id defines the unique ID of the geometry
  40171. * @param scene defines the hosting scene
  40172. * @param xmin defines the minimum value on X axis
  40173. * @param zmin defines the minimum value on Z axis
  40174. * @param xmax defines the maximum value on X axis
  40175. * @param zmax defines the maximum value on Z axis
  40176. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40177. * @param precision defines the precision to use when computing the tiles
  40178. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40179. * @param mesh defines the hosting mesh (can be null)
  40180. */
  40181. function TiledGroundGeometry(id, scene,
  40182. /**
  40183. * Defines the minimum value on X axis
  40184. */
  40185. xmin,
  40186. /**
  40187. * Defines the minimum value on Z axis
  40188. */
  40189. zmin,
  40190. /**
  40191. * Defines the maximum value on X axis
  40192. */
  40193. xmax,
  40194. /**
  40195. * Defines the maximum value on Z axis
  40196. */
  40197. zmax,
  40198. /**
  40199. * Defines the subdivisions to apply to the ground
  40200. */
  40201. subdivisions,
  40202. /**
  40203. * Defines the precision to use when computing the tiles
  40204. */
  40205. precision, canBeRegenerated, mesh) {
  40206. if (mesh === void 0) { mesh = null; }
  40207. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40208. _this.xmin = xmin;
  40209. _this.zmin = zmin;
  40210. _this.xmax = xmax;
  40211. _this.zmax = zmax;
  40212. _this.subdivisions = subdivisions;
  40213. _this.precision = precision;
  40214. return _this;
  40215. }
  40216. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40217. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40218. };
  40219. TiledGroundGeometry.prototype.copy = function (id) {
  40220. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40221. };
  40222. return TiledGroundGeometry;
  40223. }(_PrimitiveGeometry));
  40224. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40225. /**
  40226. * Creates a plane geometry
  40227. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40228. */
  40229. var PlaneGeometry = /** @class */ (function (_super) {
  40230. __extends(PlaneGeometry, _super);
  40231. /**
  40232. * Creates a plane geometry
  40233. * @param id defines the unique ID of the geometry
  40234. * @param scene defines the hosting scene
  40235. * @param size defines the size of the plane (width === height)
  40236. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40237. * @param mesh defines the hosting mesh (can be null)
  40238. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40239. */
  40240. function PlaneGeometry(id, scene,
  40241. /**
  40242. * Defines the size of the plane (width === height)
  40243. */
  40244. size, canBeRegenerated, mesh,
  40245. /**
  40246. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40247. */
  40248. side) {
  40249. if (mesh === void 0) { mesh = null; }
  40250. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40251. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40252. _this.size = size;
  40253. _this.side = side;
  40254. return _this;
  40255. }
  40256. PlaneGeometry.prototype._regenerateVertexData = function () {
  40257. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40258. };
  40259. PlaneGeometry.prototype.copy = function (id) {
  40260. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40261. };
  40262. PlaneGeometry.prototype.serialize = function () {
  40263. var serializationObject = _super.prototype.serialize.call(this);
  40264. serializationObject.size = this.size;
  40265. return serializationObject;
  40266. };
  40267. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40268. if (scene.getGeometryByID(parsedPlane.id)) {
  40269. return null; // null since geometry could be something else than a ground...
  40270. }
  40271. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40272. if (BABYLON.Tags) {
  40273. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40274. }
  40275. scene.pushGeometry(plane, true);
  40276. return plane;
  40277. };
  40278. return PlaneGeometry;
  40279. }(_PrimitiveGeometry));
  40280. BABYLON.PlaneGeometry = PlaneGeometry;
  40281. /**
  40282. * Creates a torus knot geometry
  40283. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40284. */
  40285. var TorusKnotGeometry = /** @class */ (function (_super) {
  40286. __extends(TorusKnotGeometry, _super);
  40287. /**
  40288. * Creates a torus knot geometry
  40289. * @param id defines the unique ID of the geometry
  40290. * @param scene defines the hosting scene
  40291. * @param radius defines the radius of the torus knot
  40292. * @param tube defines the thickness of the torus knot tube
  40293. * @param radialSegments defines the number of radial segments
  40294. * @param tubularSegments defines the number of tubular segments
  40295. * @param p defines the first number of windings
  40296. * @param q defines the second number of windings
  40297. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40298. * @param mesh defines the hosting mesh (can be null)
  40299. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40300. */
  40301. function TorusKnotGeometry(id, scene,
  40302. /**
  40303. * Defines the radius of the torus knot
  40304. */
  40305. radius,
  40306. /**
  40307. * Defines the thickness of the torus knot tube
  40308. */
  40309. tube,
  40310. /**
  40311. * Defines the number of radial segments
  40312. */
  40313. radialSegments,
  40314. /**
  40315. * Defines the number of tubular segments
  40316. */
  40317. tubularSegments,
  40318. /**
  40319. * Defines the first number of windings
  40320. */
  40321. p,
  40322. /**
  40323. * Defines the second number of windings
  40324. */
  40325. q, canBeRegenerated, mesh,
  40326. /**
  40327. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40328. */
  40329. side) {
  40330. if (mesh === void 0) { mesh = null; }
  40331. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40332. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40333. _this.radius = radius;
  40334. _this.tube = tube;
  40335. _this.radialSegments = radialSegments;
  40336. _this.tubularSegments = tubularSegments;
  40337. _this.p = p;
  40338. _this.q = q;
  40339. _this.side = side;
  40340. return _this;
  40341. }
  40342. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40343. 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 });
  40344. };
  40345. TorusKnotGeometry.prototype.copy = function (id) {
  40346. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40347. };
  40348. TorusKnotGeometry.prototype.serialize = function () {
  40349. var serializationObject = _super.prototype.serialize.call(this);
  40350. serializationObject.radius = this.radius;
  40351. serializationObject.tube = this.tube;
  40352. serializationObject.radialSegments = this.radialSegments;
  40353. serializationObject.tubularSegments = this.tubularSegments;
  40354. serializationObject.p = this.p;
  40355. serializationObject.q = this.q;
  40356. return serializationObject;
  40357. };
  40358. ;
  40359. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40360. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40361. return null; // null since geometry could be something else than a ground...
  40362. }
  40363. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40364. if (BABYLON.Tags) {
  40365. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40366. }
  40367. scene.pushGeometry(torusKnot, true);
  40368. return torusKnot;
  40369. };
  40370. return TorusKnotGeometry;
  40371. }(_PrimitiveGeometry));
  40372. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40373. //}
  40374. })(BABYLON || (BABYLON = {}));
  40375. //# sourceMappingURL=babylon.geometry.js.map
  40376. var BABYLON;
  40377. (function (BABYLON) {
  40378. /**
  40379. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40380. */
  40381. var PerformanceMonitor = /** @class */ (function () {
  40382. /**
  40383. * constructor
  40384. * @param frameSampleSize The number of samples required to saturate the sliding window
  40385. */
  40386. function PerformanceMonitor(frameSampleSize) {
  40387. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40388. this._enabled = true;
  40389. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40390. }
  40391. /**
  40392. * Samples current frame
  40393. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40394. */
  40395. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40396. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40397. if (!this._enabled)
  40398. return;
  40399. if (this._lastFrameTimeMs != null) {
  40400. var dt = timeMs - this._lastFrameTimeMs;
  40401. this._rollingFrameTime.add(dt);
  40402. }
  40403. this._lastFrameTimeMs = timeMs;
  40404. };
  40405. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40406. /**
  40407. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40408. * @return Average frame time in milliseconds
  40409. */
  40410. get: function () {
  40411. return this._rollingFrameTime.average;
  40412. },
  40413. enumerable: true,
  40414. configurable: true
  40415. });
  40416. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40417. /**
  40418. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40419. * @return Frame time variance in milliseconds squared
  40420. */
  40421. get: function () {
  40422. return this._rollingFrameTime.variance;
  40423. },
  40424. enumerable: true,
  40425. configurable: true
  40426. });
  40427. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40428. /**
  40429. * Returns the frame time of the most recent frame
  40430. * @return Frame time in milliseconds
  40431. */
  40432. get: function () {
  40433. return this._rollingFrameTime.history(0);
  40434. },
  40435. enumerable: true,
  40436. configurable: true
  40437. });
  40438. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40439. /**
  40440. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40441. * @return Framerate in frames per second
  40442. */
  40443. get: function () {
  40444. return 1000.0 / this._rollingFrameTime.average;
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40450. /**
  40451. * Returns the average framerate in frames per second using the most recent frame time
  40452. * @return Framerate in frames per second
  40453. */
  40454. get: function () {
  40455. var history = this._rollingFrameTime.history(0);
  40456. if (history === 0) {
  40457. return 0;
  40458. }
  40459. return 1000.0 / history;
  40460. },
  40461. enumerable: true,
  40462. configurable: true
  40463. });
  40464. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40465. /**
  40466. * Returns true if enough samples have been taken to completely fill the sliding window
  40467. * @return true if saturated
  40468. */
  40469. get: function () {
  40470. return this._rollingFrameTime.isSaturated();
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. /**
  40476. * Enables contributions to the sliding window sample set
  40477. */
  40478. PerformanceMonitor.prototype.enable = function () {
  40479. this._enabled = true;
  40480. };
  40481. /**
  40482. * Disables contributions to the sliding window sample set
  40483. * Samples will not be interpolated over the disabled period
  40484. */
  40485. PerformanceMonitor.prototype.disable = function () {
  40486. this._enabled = false;
  40487. //clear last sample to avoid interpolating over the disabled period when next enabled
  40488. this._lastFrameTimeMs = null;
  40489. };
  40490. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40491. /**
  40492. * Returns true if sampling is enabled
  40493. * @return true if enabled
  40494. */
  40495. get: function () {
  40496. return this._enabled;
  40497. },
  40498. enumerable: true,
  40499. configurable: true
  40500. });
  40501. /**
  40502. * Resets performance monitor
  40503. */
  40504. PerformanceMonitor.prototype.reset = function () {
  40505. //clear last sample to avoid interpolating over the disabled period when next enabled
  40506. this._lastFrameTimeMs = null;
  40507. //wipe record
  40508. this._rollingFrameTime.reset();
  40509. };
  40510. return PerformanceMonitor;
  40511. }());
  40512. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40513. /**
  40514. * RollingAverage
  40515. *
  40516. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40517. */
  40518. var RollingAverage = /** @class */ (function () {
  40519. /**
  40520. * constructor
  40521. * @param length The number of samples required to saturate the sliding window
  40522. */
  40523. function RollingAverage(length) {
  40524. this._samples = new Array(length);
  40525. this.reset();
  40526. }
  40527. /**
  40528. * Adds a sample to the sample set
  40529. * @param v The sample value
  40530. */
  40531. RollingAverage.prototype.add = function (v) {
  40532. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40533. var delta;
  40534. //we need to check if we've already wrapped round
  40535. if (this.isSaturated()) {
  40536. //remove bottom of stack from mean
  40537. var bottomValue = this._samples[this._pos];
  40538. delta = bottomValue - this.average;
  40539. this.average -= delta / (this._sampleCount - 1);
  40540. this._m2 -= delta * (bottomValue - this.average);
  40541. }
  40542. else {
  40543. this._sampleCount++;
  40544. }
  40545. //add new value to mean
  40546. delta = v - this.average;
  40547. this.average += delta / (this._sampleCount);
  40548. this._m2 += delta * (v - this.average);
  40549. //set the new variance
  40550. this.variance = this._m2 / (this._sampleCount - 1);
  40551. this._samples[this._pos] = v;
  40552. this._pos++;
  40553. this._pos %= this._samples.length; //positive wrap around
  40554. };
  40555. /**
  40556. * Returns previously added values or null if outside of history or outside the sliding window domain
  40557. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40558. * @return Value previously recorded with add() or null if outside of range
  40559. */
  40560. RollingAverage.prototype.history = function (i) {
  40561. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40562. return 0;
  40563. }
  40564. var i0 = this._wrapPosition(this._pos - 1.0);
  40565. return this._samples[this._wrapPosition(i0 - i)];
  40566. };
  40567. /**
  40568. * Returns true if enough samples have been taken to completely fill the sliding window
  40569. * @return true if sample-set saturated
  40570. */
  40571. RollingAverage.prototype.isSaturated = function () {
  40572. return this._sampleCount >= this._samples.length;
  40573. };
  40574. /**
  40575. * Resets the rolling average (equivalent to 0 samples taken so far)
  40576. */
  40577. RollingAverage.prototype.reset = function () {
  40578. this.average = 0;
  40579. this.variance = 0;
  40580. this._sampleCount = 0;
  40581. this._pos = 0;
  40582. this._m2 = 0;
  40583. };
  40584. /**
  40585. * Wraps a value around the sample range boundaries
  40586. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40587. * @return Wrapped position in sample range
  40588. */
  40589. RollingAverage.prototype._wrapPosition = function (i) {
  40590. var max = this._samples.length;
  40591. return ((i % max) + max) % max;
  40592. };
  40593. return RollingAverage;
  40594. }());
  40595. BABYLON.RollingAverage = RollingAverage;
  40596. })(BABYLON || (BABYLON = {}));
  40597. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40598. var BABYLON;
  40599. (function (BABYLON) {
  40600. /**
  40601. * "Static Class" containing the most commonly used helper while dealing with material for
  40602. * rendering purpose.
  40603. *
  40604. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40605. *
  40606. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40607. */
  40608. var MaterialHelper = /** @class */ (function () {
  40609. function MaterialHelper() {
  40610. }
  40611. /**
  40612. * Bind the current view position to an effect.
  40613. * @param effect The effect to be bound
  40614. * @param scene The scene the eyes position is used from
  40615. */
  40616. MaterialHelper.BindEyePosition = function (effect, scene) {
  40617. if (scene._forcedViewPosition) {
  40618. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40619. return;
  40620. }
  40621. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40622. };
  40623. /**
  40624. * Helps preparing the defines values about the UVs in used in the effect.
  40625. * UVs are shared as much as we can accross chanels in the shaders.
  40626. * @param texture The texture we are preparing the UVs for
  40627. * @param defines The defines to update
  40628. * @param key The chanel key "diffuse", "specular"... used in the shader
  40629. */
  40630. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40631. defines._needUVs = true;
  40632. defines[key] = true;
  40633. if (texture.getTextureMatrix().isIdentity(true)) {
  40634. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40635. if (texture.coordinatesIndex === 0) {
  40636. defines["MAINUV1"] = true;
  40637. }
  40638. else {
  40639. defines["MAINUV2"] = true;
  40640. }
  40641. }
  40642. else {
  40643. defines[key + "DIRECTUV"] = 0;
  40644. }
  40645. };
  40646. /**
  40647. * Binds a texture matrix value to its corrsponding uniform
  40648. * @param texture The texture to bind the matrix for
  40649. * @param uniformBuffer The uniform buffer receivin the data
  40650. * @param key The chanel key "diffuse", "specular"... used in the shader
  40651. */
  40652. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40653. var matrix = texture.getTextureMatrix();
  40654. if (!matrix.isIdentity(true)) {
  40655. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40656. }
  40657. };
  40658. /**
  40659. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40660. * @param mesh defines the current mesh
  40661. * @param scene defines the current scene
  40662. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40663. * @param pointsCloud defines if point cloud rendering has to be turned on
  40664. * @param fogEnabled defines if fog has to be turned on
  40665. * @param alphaTest defines if alpha testing has to be turned on
  40666. * @param defines defines the current list of defines
  40667. */
  40668. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40669. if (defines._areMiscDirty) {
  40670. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40671. defines["POINTSIZE"] = pointsCloud;
  40672. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40673. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40674. defines["ALPHATEST"] = alphaTest;
  40675. }
  40676. };
  40677. /**
  40678. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40679. * @param scene defines the current scene
  40680. * @param engine defines the current engine
  40681. * @param defines specifies the list of active defines
  40682. * @param useInstances defines if instances have to be turned on
  40683. * @param useClipPlane defines if clip plane have to be turned on
  40684. */
  40685. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40686. if (useClipPlane === void 0) { useClipPlane = null; }
  40687. var changed = false;
  40688. if (useClipPlane == null) {
  40689. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  40690. }
  40691. if (defines["CLIPPLANE"] !== useClipPlane) {
  40692. defines["CLIPPLANE"] = useClipPlane;
  40693. changed = true;
  40694. }
  40695. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40696. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40697. changed = true;
  40698. }
  40699. if (defines["INSTANCES"] !== useInstances) {
  40700. defines["INSTANCES"] = useInstances;
  40701. changed = true;
  40702. }
  40703. if (changed) {
  40704. defines.markAsUnprocessed();
  40705. }
  40706. };
  40707. /**
  40708. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40709. * @param mesh The mesh containing the geometry data we will draw
  40710. * @param defines The defines to update
  40711. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40712. * @param useBones Precise whether bones should be used or not (override mesh info)
  40713. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40714. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40715. * @returns false if defines are considered not dirty and have not been checked
  40716. */
  40717. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40718. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40719. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40720. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40721. return false;
  40722. }
  40723. defines._normals = defines._needNormals;
  40724. defines._uvs = defines._needUVs;
  40725. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40726. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40727. defines["TANGENT"] = true;
  40728. }
  40729. if (defines._needUVs) {
  40730. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40731. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40732. }
  40733. else {
  40734. defines["UV1"] = false;
  40735. defines["UV2"] = false;
  40736. }
  40737. if (useVertexColor) {
  40738. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40739. defines["VERTEXCOLOR"] = hasVertexColors;
  40740. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40741. }
  40742. if (useBones) {
  40743. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40744. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40745. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40746. }
  40747. else {
  40748. defines["NUM_BONE_INFLUENCERS"] = 0;
  40749. defines["BonesPerMesh"] = 0;
  40750. }
  40751. }
  40752. if (useMorphTargets) {
  40753. var manager = mesh.morphTargetManager;
  40754. if (manager) {
  40755. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40756. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40757. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40758. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40759. }
  40760. else {
  40761. defines["MORPHTARGETS_TANGENT"] = false;
  40762. defines["MORPHTARGETS_NORMAL"] = false;
  40763. defines["MORPHTARGETS"] = false;
  40764. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40765. }
  40766. }
  40767. return true;
  40768. };
  40769. /**
  40770. * Prepares the defines related to the light information passed in parameter
  40771. * @param scene The scene we are intending to draw
  40772. * @param mesh The mesh the effect is compiling for
  40773. * @param defines The defines to update
  40774. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40775. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40776. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40777. * @returns true if normals will be required for the rest of the effect
  40778. */
  40779. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40780. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40781. if (disableLighting === void 0) { disableLighting = false; }
  40782. if (!defines._areLightsDirty) {
  40783. return defines._needNormals;
  40784. }
  40785. var lightIndex = 0;
  40786. var needNormals = false;
  40787. var needRebuild = false;
  40788. var lightmapMode = false;
  40789. var shadowEnabled = false;
  40790. var specularEnabled = false;
  40791. if (scene.lightsEnabled && !disableLighting) {
  40792. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40793. var light = _a[_i];
  40794. needNormals = true;
  40795. if (defines["LIGHT" + lightIndex] === undefined) {
  40796. needRebuild = true;
  40797. }
  40798. defines["LIGHT" + lightIndex] = true;
  40799. defines["SPOTLIGHT" + lightIndex] = false;
  40800. defines["HEMILIGHT" + lightIndex] = false;
  40801. defines["POINTLIGHT" + lightIndex] = false;
  40802. defines["DIRLIGHT" + lightIndex] = false;
  40803. light.prepareLightSpecificDefines(defines, lightIndex);
  40804. // Specular
  40805. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40806. specularEnabled = true;
  40807. }
  40808. // Shadows
  40809. defines["SHADOW" + lightIndex] = false;
  40810. defines["SHADOWPCF" + lightIndex] = false;
  40811. defines["SHADOWPCSS" + lightIndex] = false;
  40812. defines["SHADOWPOISSON" + lightIndex] = false;
  40813. defines["SHADOWESM" + lightIndex] = false;
  40814. defines["SHADOWCUBE" + lightIndex] = false;
  40815. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40816. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40817. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40818. var shadowGenerator = light.getShadowGenerator();
  40819. if (shadowGenerator) {
  40820. var shadowMap = shadowGenerator.getShadowMap();
  40821. if (shadowMap) {
  40822. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40823. shadowEnabled = true;
  40824. shadowGenerator.prepareDefines(defines, lightIndex);
  40825. }
  40826. }
  40827. }
  40828. }
  40829. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40830. lightmapMode = true;
  40831. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  40832. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  40833. }
  40834. else {
  40835. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  40836. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  40837. }
  40838. lightIndex++;
  40839. if (lightIndex === maxSimultaneousLights)
  40840. break;
  40841. }
  40842. }
  40843. defines["SPECULARTERM"] = specularEnabled;
  40844. defines["SHADOWS"] = shadowEnabled;
  40845. // Resetting all other lights if any
  40846. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  40847. if (defines["LIGHT" + index] !== undefined) {
  40848. defines["LIGHT" + index] = false;
  40849. defines["HEMILIGHT" + lightIndex] = false;
  40850. defines["POINTLIGHT" + lightIndex] = false;
  40851. defines["DIRLIGHT" + lightIndex] = false;
  40852. defines["SPOTLIGHT" + lightIndex] = false;
  40853. defines["SHADOW" + lightIndex] = false;
  40854. }
  40855. }
  40856. var caps = scene.getEngine().getCaps();
  40857. if (defines["SHADOWFLOAT"] === undefined) {
  40858. needRebuild = true;
  40859. }
  40860. defines["SHADOWFLOAT"] = shadowEnabled &&
  40861. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  40862. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  40863. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  40864. if (needRebuild) {
  40865. defines.rebuild();
  40866. }
  40867. return needNormals;
  40868. };
  40869. /**
  40870. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  40871. * that won t be acctive due to defines being turned off.
  40872. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  40873. * @param samplersList The samplers list
  40874. * @param defines The defines helping in the list generation
  40875. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  40876. */
  40877. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  40878. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40879. var uniformsList;
  40880. var uniformBuffersList = null;
  40881. if (uniformsListOrOptions.uniformsNames) {
  40882. var options = uniformsListOrOptions;
  40883. uniformsList = options.uniformsNames;
  40884. uniformBuffersList = options.uniformBuffersNames;
  40885. samplersList = options.samplers;
  40886. defines = options.defines;
  40887. maxSimultaneousLights = options.maxSimultaneousLights;
  40888. }
  40889. else {
  40890. uniformsList = uniformsListOrOptions;
  40891. if (!samplersList) {
  40892. samplersList = [];
  40893. }
  40894. }
  40895. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40896. if (!defines["LIGHT" + lightIndex]) {
  40897. break;
  40898. }
  40899. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  40900. if (uniformBuffersList) {
  40901. uniformBuffersList.push("Light" + lightIndex);
  40902. }
  40903. samplersList.push("shadowSampler" + lightIndex);
  40904. samplersList.push("depthSampler" + lightIndex);
  40905. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  40906. samplersList.push("projectionLightSampler" + lightIndex);
  40907. uniformsList.push("textureProjectionMatrix" + lightIndex);
  40908. }
  40909. }
  40910. if (defines["NUM_MORPH_INFLUENCERS"]) {
  40911. uniformsList.push("morphTargetInfluences");
  40912. }
  40913. };
  40914. /**
  40915. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  40916. * @param defines The defines to update while falling back
  40917. * @param fallbacks The authorized effect fallbacks
  40918. * @param maxSimultaneousLights The maximum number of lights allowed
  40919. * @param rank the current rank of the Effect
  40920. * @returns The newly affected rank
  40921. */
  40922. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  40923. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40924. if (rank === void 0) { rank = 0; }
  40925. var lightFallbackRank = 0;
  40926. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  40927. if (!defines["LIGHT" + lightIndex]) {
  40928. break;
  40929. }
  40930. if (lightIndex > 0) {
  40931. lightFallbackRank = rank + lightIndex;
  40932. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  40933. }
  40934. if (!defines["SHADOWS"]) {
  40935. if (defines["SHADOW" + lightIndex]) {
  40936. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  40937. }
  40938. if (defines["SHADOWPCF" + lightIndex]) {
  40939. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  40940. }
  40941. if (defines["SHADOWPCSS" + lightIndex]) {
  40942. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  40943. }
  40944. if (defines["SHADOWPOISSON" + lightIndex]) {
  40945. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  40946. }
  40947. if (defines["SHADOWESM" + lightIndex]) {
  40948. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  40949. }
  40950. }
  40951. }
  40952. return lightFallbackRank++;
  40953. };
  40954. /**
  40955. * Prepares the list of attributes required for morph targets according to the effect defines.
  40956. * @param attribs The current list of supported attribs
  40957. * @param mesh The mesh to prepare the morph targets attributes for
  40958. * @param defines The current Defines of the effect
  40959. */
  40960. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  40961. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  40962. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  40963. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  40964. var manager = mesh.morphTargetManager;
  40965. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  40966. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  40967. for (var index = 0; index < influencers; index++) {
  40968. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  40969. if (normal) {
  40970. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  40971. }
  40972. if (tangent) {
  40973. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  40974. }
  40975. if (attribs.length > maxAttributesCount) {
  40976. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  40977. }
  40978. }
  40979. }
  40980. };
  40981. /**
  40982. * Prepares the list of attributes required for bones according to the effect defines.
  40983. * @param attribs The current list of supported attribs
  40984. * @param mesh The mesh to prepare the bones attributes for
  40985. * @param defines The current Defines of the effect
  40986. * @param fallbacks The current efffect fallback strategy
  40987. */
  40988. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  40989. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  40990. fallbacks.addCPUSkinningFallback(0, mesh);
  40991. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40992. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40993. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  40994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40996. }
  40997. }
  40998. };
  40999. /**
  41000. * Prepares the list of attributes required for instances according to the effect defines.
  41001. * @param attribs The current list of supported attribs
  41002. * @param defines The current Defines of the effect
  41003. */
  41004. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41005. if (defines["INSTANCES"]) {
  41006. attribs.push("world0");
  41007. attribs.push("world1");
  41008. attribs.push("world2");
  41009. attribs.push("world3");
  41010. }
  41011. };
  41012. /**
  41013. * Binds the light shadow information to the effect for the given mesh.
  41014. * @param light The light containing the generator
  41015. * @param scene The scene the lights belongs to
  41016. * @param mesh The mesh we are binding the information to render
  41017. * @param lightIndex The light index in the effect used to render the mesh
  41018. * @param effect The effect we are binding the data to
  41019. */
  41020. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41021. if (light.shadowEnabled && mesh.receiveShadows) {
  41022. var shadowGenerator = light.getShadowGenerator();
  41023. if (shadowGenerator) {
  41024. shadowGenerator.bindShadowLight(lightIndex, effect);
  41025. }
  41026. }
  41027. };
  41028. /**
  41029. * Binds the light information to the effect.
  41030. * @param light The light containing the generator
  41031. * @param effect The effect we are binding the data to
  41032. * @param lightIndex The light index in the effect used to render
  41033. */
  41034. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41035. light.transferToEffect(effect, lightIndex + "");
  41036. };
  41037. /**
  41038. * Binds the lights information from the scene to the effect for the given mesh.
  41039. * @param scene The scene the lights belongs to
  41040. * @param mesh The mesh we are binding the information to render
  41041. * @param effect The effect we are binding the data to
  41042. * @param defines The generated defines for the effect
  41043. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41044. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41045. */
  41046. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41047. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41048. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41049. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41050. for (var i = 0; i < len; i++) {
  41051. var light = mesh._lightSources[i];
  41052. var iAsString = i.toString();
  41053. var scaledIntensity = light.getScaledIntensity();
  41054. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41055. MaterialHelper.BindLightProperties(light, effect, i);
  41056. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41057. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41058. if (defines["SPECULARTERM"]) {
  41059. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41060. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41061. }
  41062. // Shadows
  41063. if (scene.shadowsEnabled) {
  41064. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41065. }
  41066. light._uniformBuffer.update();
  41067. }
  41068. };
  41069. /**
  41070. * Binds the fog information from the scene to the effect for the given mesh.
  41071. * @param scene The scene the lights belongs to
  41072. * @param mesh The mesh we are binding the information to render
  41073. * @param effect The effect we are binding the data to
  41074. */
  41075. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41076. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41077. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41078. effect.setColor3("vFogColor", scene.fogColor);
  41079. }
  41080. };
  41081. /**
  41082. * Binds the bones information from the mesh to the effect.
  41083. * @param mesh The mesh we are binding the information to render
  41084. * @param effect The effect we are binding the data to
  41085. */
  41086. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41087. if (!effect || !mesh) {
  41088. return;
  41089. }
  41090. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41091. mesh.computeBonesUsingShaders = false;
  41092. }
  41093. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41094. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41095. if (matrices) {
  41096. effect.setMatrices("mBones", matrices);
  41097. }
  41098. }
  41099. };
  41100. /**
  41101. * Binds the morph targets information from the mesh to the effect.
  41102. * @param abstractMesh The mesh we are binding the information to render
  41103. * @param effect The effect we are binding the data to
  41104. */
  41105. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41106. var manager = abstractMesh.morphTargetManager;
  41107. if (!abstractMesh || !manager) {
  41108. return;
  41109. }
  41110. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41111. };
  41112. /**
  41113. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41114. * @param defines The generated defines used in the effect
  41115. * @param effect The effect we are binding the data to
  41116. * @param scene The scene we are willing to render with logarithmic scale for
  41117. */
  41118. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41119. if (defines["LOGARITHMICDEPTH"]) {
  41120. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41121. }
  41122. };
  41123. /**
  41124. * Binds the clip plane information from the scene to the effect.
  41125. * @param scene The scene the clip plane information are extracted from
  41126. * @param effect The effect we are binding the data to
  41127. */
  41128. MaterialHelper.BindClipPlane = function (effect, scene) {
  41129. if (scene.clipPlane) {
  41130. var clipPlane = scene.clipPlane;
  41131. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41132. }
  41133. };
  41134. return MaterialHelper;
  41135. }());
  41136. BABYLON.MaterialHelper = MaterialHelper;
  41137. })(BABYLON || (BABYLON = {}));
  41138. //# sourceMappingURL=babylon.materialHelper.js.map
  41139. var BABYLON;
  41140. (function (BABYLON) {
  41141. var PushMaterial = /** @class */ (function (_super) {
  41142. __extends(PushMaterial, _super);
  41143. function PushMaterial(name, scene) {
  41144. var _this = _super.call(this, name, scene) || this;
  41145. _this._normalMatrix = new BABYLON.Matrix();
  41146. _this.storeEffectOnSubMeshes = true;
  41147. return _this;
  41148. }
  41149. PushMaterial.prototype.getEffect = function () {
  41150. return this._activeEffect;
  41151. };
  41152. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41153. if (!mesh) {
  41154. return false;
  41155. }
  41156. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41157. return true;
  41158. }
  41159. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41160. };
  41161. /**
  41162. * Binds the given world matrix to the active effect
  41163. *
  41164. * @param world the matrix to bind
  41165. */
  41166. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41167. this._activeEffect.setMatrix("world", world);
  41168. };
  41169. /**
  41170. * Binds the given normal matrix to the active effect
  41171. *
  41172. * @param normalMatrix the matrix to bind
  41173. */
  41174. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41175. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41176. };
  41177. PushMaterial.prototype.bind = function (world, mesh) {
  41178. if (!mesh) {
  41179. return;
  41180. }
  41181. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41182. };
  41183. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41184. if (effect === void 0) { effect = null; }
  41185. _super.prototype._afterBind.call(this, mesh);
  41186. this.getScene()._cachedEffect = effect;
  41187. };
  41188. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41189. if (visibility === void 0) { visibility = 1; }
  41190. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41191. };
  41192. return PushMaterial;
  41193. }(BABYLON.Material));
  41194. BABYLON.PushMaterial = PushMaterial;
  41195. })(BABYLON || (BABYLON = {}));
  41196. //# sourceMappingURL=babylon.pushMaterial.js.map
  41197. var BABYLON;
  41198. (function (BABYLON) {
  41199. /** @hidden */
  41200. var StandardMaterialDefines = /** @class */ (function (_super) {
  41201. __extends(StandardMaterialDefines, _super);
  41202. function StandardMaterialDefines() {
  41203. var _this = _super.call(this) || this;
  41204. _this.MAINUV1 = false;
  41205. _this.MAINUV2 = false;
  41206. _this.DIFFUSE = false;
  41207. _this.DIFFUSEDIRECTUV = 0;
  41208. _this.AMBIENT = false;
  41209. _this.AMBIENTDIRECTUV = 0;
  41210. _this.OPACITY = false;
  41211. _this.OPACITYDIRECTUV = 0;
  41212. _this.OPACITYRGB = false;
  41213. _this.REFLECTION = false;
  41214. _this.EMISSIVE = false;
  41215. _this.EMISSIVEDIRECTUV = 0;
  41216. _this.SPECULAR = false;
  41217. _this.SPECULARDIRECTUV = 0;
  41218. _this.BUMP = false;
  41219. _this.BUMPDIRECTUV = 0;
  41220. _this.PARALLAX = false;
  41221. _this.PARALLAXOCCLUSION = false;
  41222. _this.SPECULAROVERALPHA = false;
  41223. _this.CLIPPLANE = false;
  41224. _this.ALPHATEST = false;
  41225. _this.DEPTHPREPASS = false;
  41226. _this.ALPHAFROMDIFFUSE = false;
  41227. _this.POINTSIZE = false;
  41228. _this.FOG = false;
  41229. _this.SPECULARTERM = false;
  41230. _this.DIFFUSEFRESNEL = false;
  41231. _this.OPACITYFRESNEL = false;
  41232. _this.REFLECTIONFRESNEL = false;
  41233. _this.REFRACTIONFRESNEL = false;
  41234. _this.EMISSIVEFRESNEL = false;
  41235. _this.FRESNEL = false;
  41236. _this.NORMAL = false;
  41237. _this.UV1 = false;
  41238. _this.UV2 = false;
  41239. _this.VERTEXCOLOR = false;
  41240. _this.VERTEXALPHA = false;
  41241. _this.NUM_BONE_INFLUENCERS = 0;
  41242. _this.BonesPerMesh = 0;
  41243. _this.INSTANCES = false;
  41244. _this.GLOSSINESS = false;
  41245. _this.ROUGHNESS = false;
  41246. _this.EMISSIVEASILLUMINATION = false;
  41247. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41248. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41249. _this.LIGHTMAP = false;
  41250. _this.LIGHTMAPDIRECTUV = 0;
  41251. _this.OBJECTSPACE_NORMALMAP = false;
  41252. _this.USELIGHTMAPASSHADOWMAP = false;
  41253. _this.REFLECTIONMAP_3D = false;
  41254. _this.REFLECTIONMAP_SPHERICAL = false;
  41255. _this.REFLECTIONMAP_PLANAR = false;
  41256. _this.REFLECTIONMAP_CUBIC = false;
  41257. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41258. _this.REFLECTIONMAP_PROJECTION = false;
  41259. _this.REFLECTIONMAP_SKYBOX = false;
  41260. _this.REFLECTIONMAP_EXPLICIT = false;
  41261. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41262. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41263. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41264. _this.INVERTCUBICMAP = false;
  41265. _this.LOGARITHMICDEPTH = false;
  41266. _this.REFRACTION = false;
  41267. _this.REFRACTIONMAP_3D = false;
  41268. _this.REFLECTIONOVERALPHA = false;
  41269. _this.TWOSIDEDLIGHTING = false;
  41270. _this.SHADOWFLOAT = false;
  41271. _this.MORPHTARGETS = false;
  41272. _this.MORPHTARGETS_NORMAL = false;
  41273. _this.MORPHTARGETS_TANGENT = false;
  41274. _this.NUM_MORPH_INFLUENCERS = 0;
  41275. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41276. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41277. _this.IMAGEPROCESSING = false;
  41278. _this.VIGNETTE = false;
  41279. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41280. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41281. _this.TONEMAPPING = false;
  41282. _this.CONTRAST = false;
  41283. _this.COLORCURVES = false;
  41284. _this.COLORGRADING = false;
  41285. _this.COLORGRADING3D = false;
  41286. _this.SAMPLER3DGREENDEPTH = false;
  41287. _this.SAMPLER3DBGRMAP = false;
  41288. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41289. /**
  41290. * If the reflection texture on this material is in linear color space
  41291. * @hidden
  41292. */
  41293. _this.IS_REFLECTION_LINEAR = false;
  41294. /**
  41295. * If the refraction texture on this material is in linear color space
  41296. * @hidden
  41297. */
  41298. _this.IS_REFRACTION_LINEAR = false;
  41299. _this.EXPOSURE = false;
  41300. _this.rebuild();
  41301. return _this;
  41302. }
  41303. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41304. var modes = [
  41305. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41306. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41307. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41308. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41309. ];
  41310. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41311. var mode = modes_1[_i];
  41312. this[mode] = (mode === modeToEnable);
  41313. }
  41314. };
  41315. return StandardMaterialDefines;
  41316. }(BABYLON.MaterialDefines));
  41317. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41318. var StandardMaterial = /** @class */ (function (_super) {
  41319. __extends(StandardMaterial, _super);
  41320. function StandardMaterial(name, scene) {
  41321. var _this = _super.call(this, name, scene) || this;
  41322. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41323. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41324. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41325. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41326. _this.specularPower = 64;
  41327. _this._useAlphaFromDiffuseTexture = false;
  41328. _this._useEmissiveAsIllumination = false;
  41329. _this._linkEmissiveWithDiffuse = false;
  41330. _this._useSpecularOverAlpha = false;
  41331. _this._useReflectionOverAlpha = false;
  41332. _this._disableLighting = false;
  41333. _this._useObjectSpaceNormalMap = false;
  41334. _this._useParallax = false;
  41335. _this._useParallaxOcclusion = false;
  41336. _this.parallaxScaleBias = 0.05;
  41337. _this._roughness = 0;
  41338. _this.indexOfRefraction = 0.98;
  41339. _this.invertRefractionY = true;
  41340. /**
  41341. * Defines the alpha limits in alpha test mode
  41342. */
  41343. _this.alphaCutOff = 0.4;
  41344. _this._useLightmapAsShadowmap = false;
  41345. _this._useReflectionFresnelFromSpecular = false;
  41346. _this._useGlossinessFromSpecularMapAlpha = false;
  41347. _this._maxSimultaneousLights = 4;
  41348. /**
  41349. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41350. */
  41351. _this._invertNormalMapX = false;
  41352. /**
  41353. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41354. */
  41355. _this._invertNormalMapY = false;
  41356. /**
  41357. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41358. */
  41359. _this._twoSidedLighting = false;
  41360. _this._renderTargets = new BABYLON.SmartArray(16);
  41361. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41362. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41363. // Setup the default processing configuration to the scene.
  41364. _this._attachImageProcessingConfiguration(null);
  41365. _this.getRenderTargetTextures = function () {
  41366. _this._renderTargets.reset();
  41367. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41368. _this._renderTargets.push(_this._reflectionTexture);
  41369. }
  41370. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41371. _this._renderTargets.push(_this._refractionTexture);
  41372. }
  41373. return _this._renderTargets;
  41374. };
  41375. return _this;
  41376. }
  41377. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41378. /**
  41379. * Gets the image processing configuration used either in this material.
  41380. */
  41381. get: function () {
  41382. return this._imageProcessingConfiguration;
  41383. },
  41384. /**
  41385. * Sets the Default image processing configuration used either in the this material.
  41386. *
  41387. * If sets to null, the scene one is in use.
  41388. */
  41389. set: function (value) {
  41390. this._attachImageProcessingConfiguration(value);
  41391. // Ensure the effect will be rebuilt.
  41392. this._markAllSubMeshesAsTexturesDirty();
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. /**
  41398. * Attaches a new image processing configuration to the Standard Material.
  41399. * @param configuration
  41400. */
  41401. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41402. var _this = this;
  41403. if (configuration === this._imageProcessingConfiguration) {
  41404. return;
  41405. }
  41406. // Detaches observer.
  41407. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41408. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41409. }
  41410. // Pick the scene configuration if needed.
  41411. if (!configuration) {
  41412. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41413. }
  41414. else {
  41415. this._imageProcessingConfiguration = configuration;
  41416. }
  41417. // Attaches observer.
  41418. if (this._imageProcessingConfiguration) {
  41419. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41420. _this._markAllSubMeshesAsImageProcessingDirty();
  41421. });
  41422. }
  41423. };
  41424. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41425. /**
  41426. * Gets wether the color curves effect is enabled.
  41427. */
  41428. get: function () {
  41429. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41430. },
  41431. /**
  41432. * Sets wether the color curves effect is enabled.
  41433. */
  41434. set: function (value) {
  41435. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41436. },
  41437. enumerable: true,
  41438. configurable: true
  41439. });
  41440. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41441. /**
  41442. * Gets wether the color grading effect is enabled.
  41443. */
  41444. get: function () {
  41445. return this.imageProcessingConfiguration.colorGradingEnabled;
  41446. },
  41447. /**
  41448. * Gets wether the color grading effect is enabled.
  41449. */
  41450. set: function (value) {
  41451. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41457. /**
  41458. * Gets wether tonemapping is enabled or not.
  41459. */
  41460. get: function () {
  41461. return this._imageProcessingConfiguration.toneMappingEnabled;
  41462. },
  41463. /**
  41464. * Sets wether tonemapping is enabled or not
  41465. */
  41466. set: function (value) {
  41467. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41468. },
  41469. enumerable: true,
  41470. configurable: true
  41471. });
  41472. ;
  41473. ;
  41474. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41475. /**
  41476. * The camera exposure used on this material.
  41477. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41478. * This corresponds to a photographic exposure.
  41479. */
  41480. get: function () {
  41481. return this._imageProcessingConfiguration.exposure;
  41482. },
  41483. /**
  41484. * The camera exposure used on this material.
  41485. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41486. * This corresponds to a photographic exposure.
  41487. */
  41488. set: function (value) {
  41489. this._imageProcessingConfiguration.exposure = value;
  41490. },
  41491. enumerable: true,
  41492. configurable: true
  41493. });
  41494. ;
  41495. ;
  41496. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41497. /**
  41498. * Gets The camera contrast used on this material.
  41499. */
  41500. get: function () {
  41501. return this._imageProcessingConfiguration.contrast;
  41502. },
  41503. /**
  41504. * Sets The camera contrast used on this material.
  41505. */
  41506. set: function (value) {
  41507. this._imageProcessingConfiguration.contrast = value;
  41508. },
  41509. enumerable: true,
  41510. configurable: true
  41511. });
  41512. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41513. /**
  41514. * Gets the Color Grading 2D Lookup Texture.
  41515. */
  41516. get: function () {
  41517. return this._imageProcessingConfiguration.colorGradingTexture;
  41518. },
  41519. /**
  41520. * Sets the Color Grading 2D Lookup Texture.
  41521. */
  41522. set: function (value) {
  41523. this._imageProcessingConfiguration.colorGradingTexture = value;
  41524. },
  41525. enumerable: true,
  41526. configurable: true
  41527. });
  41528. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41529. /**
  41530. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41531. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41532. * 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;
  41533. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41534. */
  41535. get: function () {
  41536. return this._imageProcessingConfiguration.colorCurves;
  41537. },
  41538. /**
  41539. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41540. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41541. * 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;
  41542. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41543. */
  41544. set: function (value) {
  41545. this._imageProcessingConfiguration.colorCurves = value;
  41546. },
  41547. enumerable: true,
  41548. configurable: true
  41549. });
  41550. StandardMaterial.prototype.getClassName = function () {
  41551. return "StandardMaterial";
  41552. };
  41553. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41554. get: function () {
  41555. return this._useLogarithmicDepth;
  41556. },
  41557. set: function (value) {
  41558. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41559. this._markAllSubMeshesAsMiscDirty();
  41560. },
  41561. enumerable: true,
  41562. configurable: true
  41563. });
  41564. StandardMaterial.prototype.needAlphaBlending = function () {
  41565. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41566. };
  41567. StandardMaterial.prototype.needAlphaTesting = function () {
  41568. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41569. };
  41570. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41571. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41572. };
  41573. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41574. return this._diffuseTexture;
  41575. };
  41576. /**
  41577. * Child classes can use it to update shaders
  41578. */
  41579. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41580. if (useInstances === void 0) { useInstances = false; }
  41581. if (subMesh.effect && this.isFrozen) {
  41582. if (this._wasPreviouslyReady && subMesh.effect) {
  41583. return true;
  41584. }
  41585. }
  41586. if (!subMesh._materialDefines) {
  41587. subMesh._materialDefines = new StandardMaterialDefines();
  41588. }
  41589. var scene = this.getScene();
  41590. var defines = subMesh._materialDefines;
  41591. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41592. if (defines._renderId === scene.getRenderId()) {
  41593. return true;
  41594. }
  41595. }
  41596. var engine = scene.getEngine();
  41597. // Lights
  41598. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41599. // Textures
  41600. if (defines._areTexturesDirty) {
  41601. defines._needUVs = false;
  41602. defines.MAINUV1 = false;
  41603. defines.MAINUV2 = false;
  41604. if (scene.texturesEnabled) {
  41605. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41606. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41607. return false;
  41608. }
  41609. else {
  41610. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41611. }
  41612. }
  41613. else {
  41614. defines.DIFFUSE = false;
  41615. }
  41616. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41617. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41618. return false;
  41619. }
  41620. else {
  41621. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41622. }
  41623. }
  41624. else {
  41625. defines.AMBIENT = false;
  41626. }
  41627. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41628. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41629. return false;
  41630. }
  41631. else {
  41632. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41633. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41634. }
  41635. }
  41636. else {
  41637. defines.OPACITY = false;
  41638. }
  41639. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41640. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41641. return false;
  41642. }
  41643. else {
  41644. defines._needNormals = true;
  41645. defines.REFLECTION = true;
  41646. defines.ROUGHNESS = (this._roughness > 0);
  41647. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41648. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41649. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41650. switch (this._reflectionTexture.coordinatesMode) {
  41651. case BABYLON.Texture.EXPLICIT_MODE:
  41652. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41653. break;
  41654. case BABYLON.Texture.PLANAR_MODE:
  41655. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41656. break;
  41657. case BABYLON.Texture.PROJECTION_MODE:
  41658. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41659. break;
  41660. case BABYLON.Texture.SKYBOX_MODE:
  41661. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41662. break;
  41663. case BABYLON.Texture.SPHERICAL_MODE:
  41664. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41665. break;
  41666. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41667. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41668. break;
  41669. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41670. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41671. break;
  41672. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41673. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41674. break;
  41675. case BABYLON.Texture.CUBIC_MODE:
  41676. case BABYLON.Texture.INVCUBIC_MODE:
  41677. default:
  41678. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41679. break;
  41680. }
  41681. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41682. }
  41683. }
  41684. else {
  41685. defines.REFLECTION = false;
  41686. }
  41687. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41688. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41689. return false;
  41690. }
  41691. else {
  41692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41693. }
  41694. }
  41695. else {
  41696. defines.EMISSIVE = false;
  41697. }
  41698. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41699. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41700. return false;
  41701. }
  41702. else {
  41703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41704. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41705. }
  41706. }
  41707. else {
  41708. defines.LIGHTMAP = false;
  41709. }
  41710. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41711. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41712. return false;
  41713. }
  41714. else {
  41715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41716. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41717. }
  41718. }
  41719. else {
  41720. defines.SPECULAR = false;
  41721. }
  41722. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41723. // Bump texure can not be not blocking.
  41724. if (!this._bumpTexture.isReady()) {
  41725. return false;
  41726. }
  41727. else {
  41728. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41729. defines.PARALLAX = this._useParallax;
  41730. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41731. }
  41732. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41733. }
  41734. else {
  41735. defines.BUMP = false;
  41736. }
  41737. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41738. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41739. return false;
  41740. }
  41741. else {
  41742. defines._needUVs = true;
  41743. defines.REFRACTION = true;
  41744. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41745. }
  41746. }
  41747. else {
  41748. defines.REFRACTION = false;
  41749. }
  41750. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41751. }
  41752. else {
  41753. defines.DIFFUSE = false;
  41754. defines.AMBIENT = false;
  41755. defines.OPACITY = false;
  41756. defines.REFLECTION = false;
  41757. defines.EMISSIVE = false;
  41758. defines.LIGHTMAP = false;
  41759. defines.BUMP = false;
  41760. defines.REFRACTION = false;
  41761. }
  41762. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41763. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41764. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41765. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41766. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41767. }
  41768. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41769. if (!this._imageProcessingConfiguration.isReady()) {
  41770. return false;
  41771. }
  41772. this._imageProcessingConfiguration.prepareDefines(defines);
  41773. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41774. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41775. }
  41776. if (defines._areFresnelDirty) {
  41777. if (StandardMaterial.FresnelEnabled) {
  41778. // Fresnel
  41779. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41780. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41781. this._reflectionFresnelParameters) {
  41782. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41783. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41784. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41785. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41786. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41787. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41788. defines._needNormals = true;
  41789. defines.FRESNEL = true;
  41790. }
  41791. }
  41792. else {
  41793. defines.FRESNEL = false;
  41794. }
  41795. }
  41796. // Misc.
  41797. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  41798. // Attribs
  41799. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41800. // Values that need to be evaluated on every frame
  41801. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41802. // Get correct effect
  41803. if (defines.isDirty) {
  41804. defines.markAsProcessed();
  41805. scene.resetCachedMaterial();
  41806. // Fallbacks
  41807. var fallbacks = new BABYLON.EffectFallbacks();
  41808. if (defines.REFLECTION) {
  41809. fallbacks.addFallback(0, "REFLECTION");
  41810. }
  41811. if (defines.SPECULAR) {
  41812. fallbacks.addFallback(0, "SPECULAR");
  41813. }
  41814. if (defines.BUMP) {
  41815. fallbacks.addFallback(0, "BUMP");
  41816. }
  41817. if (defines.PARALLAX) {
  41818. fallbacks.addFallback(1, "PARALLAX");
  41819. }
  41820. if (defines.PARALLAXOCCLUSION) {
  41821. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41822. }
  41823. if (defines.SPECULAROVERALPHA) {
  41824. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41825. }
  41826. if (defines.FOG) {
  41827. fallbacks.addFallback(1, "FOG");
  41828. }
  41829. if (defines.POINTSIZE) {
  41830. fallbacks.addFallback(0, "POINTSIZE");
  41831. }
  41832. if (defines.LOGARITHMICDEPTH) {
  41833. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41834. }
  41835. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41836. if (defines.SPECULARTERM) {
  41837. fallbacks.addFallback(0, "SPECULARTERM");
  41838. }
  41839. if (defines.DIFFUSEFRESNEL) {
  41840. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41841. }
  41842. if (defines.OPACITYFRESNEL) {
  41843. fallbacks.addFallback(2, "OPACITYFRESNEL");
  41844. }
  41845. if (defines.REFLECTIONFRESNEL) {
  41846. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  41847. }
  41848. if (defines.EMISSIVEFRESNEL) {
  41849. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  41850. }
  41851. if (defines.FRESNEL) {
  41852. fallbacks.addFallback(4, "FRESNEL");
  41853. }
  41854. //Attributes
  41855. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41856. if (defines.NORMAL) {
  41857. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41858. }
  41859. if (defines.UV1) {
  41860. attribs.push(BABYLON.VertexBuffer.UVKind);
  41861. }
  41862. if (defines.UV2) {
  41863. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41864. }
  41865. if (defines.VERTEXCOLOR) {
  41866. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41867. }
  41868. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41869. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41870. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41871. var shaderName = "default";
  41872. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  41873. "vFogInfos", "vFogColor", "pointSize",
  41874. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41875. "mBones",
  41876. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  41877. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  41878. "vReflectionPosition", "vReflectionSize",
  41879. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  41880. ];
  41881. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  41882. var uniformBuffers = ["Material", "Scene"];
  41883. if (BABYLON.ImageProcessingConfiguration) {
  41884. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41885. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41886. }
  41887. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41888. uniformsNames: uniforms,
  41889. uniformBuffersNames: uniformBuffers,
  41890. samplers: samplers,
  41891. defines: defines,
  41892. maxSimultaneousLights: this._maxSimultaneousLights
  41893. });
  41894. if (this.customShaderNameResolve) {
  41895. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  41896. }
  41897. var join = defines.toString();
  41898. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  41899. attributes: attribs,
  41900. uniformsNames: uniforms,
  41901. uniformBuffersNames: uniformBuffers,
  41902. samplers: samplers,
  41903. defines: join,
  41904. fallbacks: fallbacks,
  41905. onCompiled: this.onCompiled,
  41906. onError: this.onError,
  41907. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41908. }, engine), defines);
  41909. this.buildUniformLayout();
  41910. }
  41911. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41912. return false;
  41913. }
  41914. defines._renderId = scene.getRenderId();
  41915. this._wasPreviouslyReady = true;
  41916. return true;
  41917. };
  41918. StandardMaterial.prototype.buildUniformLayout = function () {
  41919. // Order is important !
  41920. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  41921. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  41922. this._uniformBuffer.addUniform("opacityParts", 4);
  41923. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  41924. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  41925. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  41926. this._uniformBuffer.addUniform("refractionRightColor", 4);
  41927. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  41928. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  41929. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  41930. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  41931. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41932. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41933. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41934. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41935. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41936. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41937. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  41938. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41939. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  41940. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41941. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41942. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41943. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41944. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41945. this._uniformBuffer.addUniform("specularMatrix", 16);
  41946. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41947. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41948. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41949. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41950. this._uniformBuffer.addUniform("vSpecularColor", 4);
  41951. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41952. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  41953. this._uniformBuffer.addUniform("pointSize", 1);
  41954. this._uniformBuffer.create();
  41955. };
  41956. StandardMaterial.prototype.unbind = function () {
  41957. if (this._activeEffect) {
  41958. var needFlag = false;
  41959. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41960. this._activeEffect.setTexture("reflection2DSampler", null);
  41961. needFlag = true;
  41962. }
  41963. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41964. this._activeEffect.setTexture("refraction2DSampler", null);
  41965. needFlag = true;
  41966. }
  41967. if (needFlag) {
  41968. this._markAllSubMeshesAsTexturesDirty();
  41969. }
  41970. }
  41971. _super.prototype.unbind.call(this);
  41972. };
  41973. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41974. var scene = this.getScene();
  41975. var defines = subMesh._materialDefines;
  41976. if (!defines) {
  41977. return;
  41978. }
  41979. var effect = subMesh.effect;
  41980. if (!effect) {
  41981. return;
  41982. }
  41983. this._activeEffect = effect;
  41984. // Matrices
  41985. this.bindOnlyWorldMatrix(world);
  41986. // Normal Matrix
  41987. if (defines.OBJECTSPACE_NORMALMAP) {
  41988. world.toNormalMatrix(this._normalMatrix);
  41989. this.bindOnlyNormalMatrix(this._normalMatrix);
  41990. }
  41991. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41992. // Bones
  41993. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  41994. if (mustRebind) {
  41995. this._uniformBuffer.bindToEffect(effect, "Material");
  41996. this.bindViewProjection(effect);
  41997. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41998. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  41999. // Fresnel
  42000. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42001. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42002. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42003. }
  42004. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42005. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42006. }
  42007. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42008. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42009. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42010. }
  42011. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42012. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42013. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42014. }
  42015. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42016. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42017. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42018. }
  42019. }
  42020. // Textures
  42021. if (scene.texturesEnabled) {
  42022. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42023. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42024. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42025. if (this._diffuseTexture.hasAlpha) {
  42026. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42027. }
  42028. }
  42029. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42030. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42031. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42032. }
  42033. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42034. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42035. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42036. }
  42037. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42038. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42039. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42040. if (this._reflectionTexture.boundingBoxSize) {
  42041. var cubeTexture = this._reflectionTexture;
  42042. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42043. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42044. }
  42045. }
  42046. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42047. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42048. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42049. }
  42050. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42051. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42052. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42053. }
  42054. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42055. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42056. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42057. }
  42058. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42059. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42060. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42061. if (scene._mirroredCameraPosition) {
  42062. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42063. }
  42064. else {
  42065. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42066. }
  42067. }
  42068. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42069. var depth = 1.0;
  42070. if (!this._refractionTexture.isCube) {
  42071. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42072. if (this._refractionTexture.depth) {
  42073. depth = this._refractionTexture.depth;
  42074. }
  42075. }
  42076. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42077. }
  42078. }
  42079. // Point size
  42080. if (this.pointsCloud) {
  42081. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42082. }
  42083. if (defines.SPECULARTERM) {
  42084. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42085. }
  42086. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42087. // Diffuse
  42088. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42089. }
  42090. // Textures
  42091. if (scene.texturesEnabled) {
  42092. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42093. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42094. }
  42095. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42096. effect.setTexture("ambientSampler", this._ambientTexture);
  42097. }
  42098. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42099. effect.setTexture("opacitySampler", this._opacityTexture);
  42100. }
  42101. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42102. if (this._reflectionTexture.isCube) {
  42103. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42104. }
  42105. else {
  42106. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42107. }
  42108. }
  42109. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42110. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42111. }
  42112. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42113. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42114. }
  42115. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42116. effect.setTexture("specularSampler", this._specularTexture);
  42117. }
  42118. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42119. effect.setTexture("bumpSampler", this._bumpTexture);
  42120. }
  42121. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42122. var depth = 1.0;
  42123. if (this._refractionTexture.isCube) {
  42124. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42125. }
  42126. else {
  42127. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42128. }
  42129. }
  42130. }
  42131. // Clip plane
  42132. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42133. // Colors
  42134. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42135. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42136. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42137. }
  42138. if (mustRebind || !this.isFrozen) {
  42139. // Lights
  42140. if (scene.lightsEnabled && !this._disableLighting) {
  42141. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42142. }
  42143. // View
  42144. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42145. this.bindView(effect);
  42146. }
  42147. // Fog
  42148. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42149. // Morph targets
  42150. if (defines.NUM_MORPH_INFLUENCERS) {
  42151. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42152. }
  42153. // Log. depth
  42154. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42155. // image processing
  42156. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42157. this._imageProcessingConfiguration.bind(this._activeEffect);
  42158. }
  42159. }
  42160. this._uniformBuffer.update();
  42161. this._afterBind(mesh, this._activeEffect);
  42162. };
  42163. StandardMaterial.prototype.getAnimatables = function () {
  42164. var results = [];
  42165. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42166. results.push(this._diffuseTexture);
  42167. }
  42168. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42169. results.push(this._ambientTexture);
  42170. }
  42171. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42172. results.push(this._opacityTexture);
  42173. }
  42174. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42175. results.push(this._reflectionTexture);
  42176. }
  42177. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42178. results.push(this._emissiveTexture);
  42179. }
  42180. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42181. results.push(this._specularTexture);
  42182. }
  42183. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42184. results.push(this._bumpTexture);
  42185. }
  42186. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42187. results.push(this._lightmapTexture);
  42188. }
  42189. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42190. results.push(this._refractionTexture);
  42191. }
  42192. return results;
  42193. };
  42194. StandardMaterial.prototype.getActiveTextures = function () {
  42195. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42196. if (this._diffuseTexture) {
  42197. activeTextures.push(this._diffuseTexture);
  42198. }
  42199. if (this._ambientTexture) {
  42200. activeTextures.push(this._ambientTexture);
  42201. }
  42202. if (this._opacityTexture) {
  42203. activeTextures.push(this._opacityTexture);
  42204. }
  42205. if (this._reflectionTexture) {
  42206. activeTextures.push(this._reflectionTexture);
  42207. }
  42208. if (this._emissiveTexture) {
  42209. activeTextures.push(this._emissiveTexture);
  42210. }
  42211. if (this._specularTexture) {
  42212. activeTextures.push(this._specularTexture);
  42213. }
  42214. if (this._bumpTexture) {
  42215. activeTextures.push(this._bumpTexture);
  42216. }
  42217. if (this._lightmapTexture) {
  42218. activeTextures.push(this._lightmapTexture);
  42219. }
  42220. if (this._refractionTexture) {
  42221. activeTextures.push(this._refractionTexture);
  42222. }
  42223. return activeTextures;
  42224. };
  42225. StandardMaterial.prototype.hasTexture = function (texture) {
  42226. if (_super.prototype.hasTexture.call(this, texture)) {
  42227. return true;
  42228. }
  42229. if (this._diffuseTexture === texture) {
  42230. return true;
  42231. }
  42232. if (this._ambientTexture === texture) {
  42233. return true;
  42234. }
  42235. if (this._opacityTexture === texture) {
  42236. return true;
  42237. }
  42238. if (this._reflectionTexture === texture) {
  42239. return true;
  42240. }
  42241. if (this._emissiveTexture === texture) {
  42242. return true;
  42243. }
  42244. if (this._specularTexture === texture) {
  42245. return true;
  42246. }
  42247. if (this._bumpTexture === texture) {
  42248. return true;
  42249. }
  42250. if (this._lightmapTexture === texture) {
  42251. return true;
  42252. }
  42253. if (this._refractionTexture === texture) {
  42254. return true;
  42255. }
  42256. return false;
  42257. };
  42258. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42259. if (forceDisposeTextures) {
  42260. if (this._diffuseTexture) {
  42261. this._diffuseTexture.dispose();
  42262. }
  42263. if (this._ambientTexture) {
  42264. this._ambientTexture.dispose();
  42265. }
  42266. if (this._opacityTexture) {
  42267. this._opacityTexture.dispose();
  42268. }
  42269. if (this._reflectionTexture) {
  42270. this._reflectionTexture.dispose();
  42271. }
  42272. if (this._emissiveTexture) {
  42273. this._emissiveTexture.dispose();
  42274. }
  42275. if (this._specularTexture) {
  42276. this._specularTexture.dispose();
  42277. }
  42278. if (this._bumpTexture) {
  42279. this._bumpTexture.dispose();
  42280. }
  42281. if (this._lightmapTexture) {
  42282. this._lightmapTexture.dispose();
  42283. }
  42284. if (this._refractionTexture) {
  42285. this._refractionTexture.dispose();
  42286. }
  42287. }
  42288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42290. }
  42291. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42292. };
  42293. StandardMaterial.prototype.clone = function (name) {
  42294. var _this = this;
  42295. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42296. result.name = name;
  42297. result.id = name;
  42298. return result;
  42299. };
  42300. StandardMaterial.prototype.serialize = function () {
  42301. return BABYLON.SerializationHelper.Serialize(this);
  42302. };
  42303. // Statics
  42304. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42305. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42306. };
  42307. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42308. get: function () {
  42309. return StandardMaterial._DiffuseTextureEnabled;
  42310. },
  42311. set: function (value) {
  42312. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42313. return;
  42314. }
  42315. StandardMaterial._DiffuseTextureEnabled = value;
  42316. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42317. },
  42318. enumerable: true,
  42319. configurable: true
  42320. });
  42321. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42322. get: function () {
  42323. return StandardMaterial._AmbientTextureEnabled;
  42324. },
  42325. set: function (value) {
  42326. if (StandardMaterial._AmbientTextureEnabled === value) {
  42327. return;
  42328. }
  42329. StandardMaterial._AmbientTextureEnabled = value;
  42330. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42331. },
  42332. enumerable: true,
  42333. configurable: true
  42334. });
  42335. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42336. get: function () {
  42337. return StandardMaterial._OpacityTextureEnabled;
  42338. },
  42339. set: function (value) {
  42340. if (StandardMaterial._OpacityTextureEnabled === value) {
  42341. return;
  42342. }
  42343. StandardMaterial._OpacityTextureEnabled = value;
  42344. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42345. },
  42346. enumerable: true,
  42347. configurable: true
  42348. });
  42349. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42350. get: function () {
  42351. return StandardMaterial._ReflectionTextureEnabled;
  42352. },
  42353. set: function (value) {
  42354. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42355. return;
  42356. }
  42357. StandardMaterial._ReflectionTextureEnabled = value;
  42358. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42359. },
  42360. enumerable: true,
  42361. configurable: true
  42362. });
  42363. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42364. get: function () {
  42365. return StandardMaterial._EmissiveTextureEnabled;
  42366. },
  42367. set: function (value) {
  42368. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42369. return;
  42370. }
  42371. StandardMaterial._EmissiveTextureEnabled = value;
  42372. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42373. },
  42374. enumerable: true,
  42375. configurable: true
  42376. });
  42377. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42378. get: function () {
  42379. return StandardMaterial._SpecularTextureEnabled;
  42380. },
  42381. set: function (value) {
  42382. if (StandardMaterial._SpecularTextureEnabled === value) {
  42383. return;
  42384. }
  42385. StandardMaterial._SpecularTextureEnabled = value;
  42386. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42387. },
  42388. enumerable: true,
  42389. configurable: true
  42390. });
  42391. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42392. get: function () {
  42393. return StandardMaterial._BumpTextureEnabled;
  42394. },
  42395. set: function (value) {
  42396. if (StandardMaterial._BumpTextureEnabled === value) {
  42397. return;
  42398. }
  42399. StandardMaterial._BumpTextureEnabled = value;
  42400. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42406. get: function () {
  42407. return StandardMaterial._LightmapTextureEnabled;
  42408. },
  42409. set: function (value) {
  42410. if (StandardMaterial._LightmapTextureEnabled === value) {
  42411. return;
  42412. }
  42413. StandardMaterial._LightmapTextureEnabled = value;
  42414. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42420. get: function () {
  42421. return StandardMaterial._RefractionTextureEnabled;
  42422. },
  42423. set: function (value) {
  42424. if (StandardMaterial._RefractionTextureEnabled === value) {
  42425. return;
  42426. }
  42427. StandardMaterial._RefractionTextureEnabled = value;
  42428. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42429. },
  42430. enumerable: true,
  42431. configurable: true
  42432. });
  42433. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42434. get: function () {
  42435. return StandardMaterial._ColorGradingTextureEnabled;
  42436. },
  42437. set: function (value) {
  42438. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42439. return;
  42440. }
  42441. StandardMaterial._ColorGradingTextureEnabled = value;
  42442. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42443. },
  42444. enumerable: true,
  42445. configurable: true
  42446. });
  42447. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42448. get: function () {
  42449. return StandardMaterial._FresnelEnabled;
  42450. },
  42451. set: function (value) {
  42452. if (StandardMaterial._FresnelEnabled === value) {
  42453. return;
  42454. }
  42455. StandardMaterial._FresnelEnabled = value;
  42456. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42457. },
  42458. enumerable: true,
  42459. configurable: true
  42460. });
  42461. // Flags used to enable or disable a type of texture for all Standard Materials
  42462. StandardMaterial._DiffuseTextureEnabled = true;
  42463. StandardMaterial._AmbientTextureEnabled = true;
  42464. StandardMaterial._OpacityTextureEnabled = true;
  42465. StandardMaterial._ReflectionTextureEnabled = true;
  42466. StandardMaterial._EmissiveTextureEnabled = true;
  42467. StandardMaterial._SpecularTextureEnabled = true;
  42468. StandardMaterial._BumpTextureEnabled = true;
  42469. StandardMaterial._LightmapTextureEnabled = true;
  42470. StandardMaterial._RefractionTextureEnabled = true;
  42471. StandardMaterial._ColorGradingTextureEnabled = true;
  42472. StandardMaterial._FresnelEnabled = true;
  42473. __decorate([
  42474. BABYLON.serializeAsTexture("diffuseTexture")
  42475. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42476. __decorate([
  42477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42478. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42479. __decorate([
  42480. BABYLON.serializeAsTexture("ambientTexture")
  42481. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42482. __decorate([
  42483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42484. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42485. __decorate([
  42486. BABYLON.serializeAsTexture("opacityTexture")
  42487. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42488. __decorate([
  42489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42490. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42491. __decorate([
  42492. BABYLON.serializeAsTexture("reflectionTexture")
  42493. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42494. __decorate([
  42495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42496. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42497. __decorate([
  42498. BABYLON.serializeAsTexture("emissiveTexture")
  42499. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42500. __decorate([
  42501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42502. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42503. __decorate([
  42504. BABYLON.serializeAsTexture("specularTexture")
  42505. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42506. __decorate([
  42507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42508. ], StandardMaterial.prototype, "specularTexture", void 0);
  42509. __decorate([
  42510. BABYLON.serializeAsTexture("bumpTexture")
  42511. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42512. __decorate([
  42513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42514. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42515. __decorate([
  42516. BABYLON.serializeAsTexture("lightmapTexture")
  42517. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42518. __decorate([
  42519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42520. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42521. __decorate([
  42522. BABYLON.serializeAsTexture("refractionTexture")
  42523. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42524. __decorate([
  42525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42526. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42527. __decorate([
  42528. BABYLON.serializeAsColor3("ambient")
  42529. ], StandardMaterial.prototype, "ambientColor", void 0);
  42530. __decorate([
  42531. BABYLON.serializeAsColor3("diffuse")
  42532. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42533. __decorate([
  42534. BABYLON.serializeAsColor3("specular")
  42535. ], StandardMaterial.prototype, "specularColor", void 0);
  42536. __decorate([
  42537. BABYLON.serializeAsColor3("emissive")
  42538. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42539. __decorate([
  42540. BABYLON.serialize()
  42541. ], StandardMaterial.prototype, "specularPower", void 0);
  42542. __decorate([
  42543. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42544. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42545. __decorate([
  42546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42547. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42548. __decorate([
  42549. BABYLON.serialize("useEmissiveAsIllumination")
  42550. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42551. __decorate([
  42552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42553. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42554. __decorate([
  42555. BABYLON.serialize("linkEmissiveWithDiffuse")
  42556. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42557. __decorate([
  42558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42559. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42560. __decorate([
  42561. BABYLON.serialize("useSpecularOverAlpha")
  42562. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42563. __decorate([
  42564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42565. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42566. __decorate([
  42567. BABYLON.serialize("useReflectionOverAlpha")
  42568. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42569. __decorate([
  42570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42571. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42572. __decorate([
  42573. BABYLON.serialize("disableLighting")
  42574. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42575. __decorate([
  42576. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42577. ], StandardMaterial.prototype, "disableLighting", void 0);
  42578. __decorate([
  42579. BABYLON.serialize("useObjectSpaceNormalMap")
  42580. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42581. __decorate([
  42582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42583. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42584. __decorate([
  42585. BABYLON.serialize("useParallax")
  42586. ], StandardMaterial.prototype, "_useParallax", void 0);
  42587. __decorate([
  42588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42589. ], StandardMaterial.prototype, "useParallax", void 0);
  42590. __decorate([
  42591. BABYLON.serialize("useParallaxOcclusion")
  42592. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42593. __decorate([
  42594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42595. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42596. __decorate([
  42597. BABYLON.serialize()
  42598. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42599. __decorate([
  42600. BABYLON.serialize("roughness")
  42601. ], StandardMaterial.prototype, "_roughness", void 0);
  42602. __decorate([
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42604. ], StandardMaterial.prototype, "roughness", void 0);
  42605. __decorate([
  42606. BABYLON.serialize()
  42607. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42608. __decorate([
  42609. BABYLON.serialize()
  42610. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42611. __decorate([
  42612. BABYLON.serialize()
  42613. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42614. __decorate([
  42615. BABYLON.serialize("useLightmapAsShadowmap")
  42616. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42617. __decorate([
  42618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42619. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42620. __decorate([
  42621. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42622. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42623. __decorate([
  42624. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42625. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42626. __decorate([
  42627. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42628. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42629. __decorate([
  42630. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42631. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42632. __decorate([
  42633. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42634. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42635. __decorate([
  42636. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42637. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42638. __decorate([
  42639. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42640. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42641. __decorate([
  42642. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42643. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42644. __decorate([
  42645. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42646. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42647. __decorate([
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42649. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42650. __decorate([
  42651. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42652. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42653. __decorate([
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42655. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42656. __decorate([
  42657. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42658. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42659. __decorate([
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42662. __decorate([
  42663. BABYLON.serialize("maxSimultaneousLights")
  42664. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42665. __decorate([
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42667. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42668. __decorate([
  42669. BABYLON.serialize("invertNormalMapX")
  42670. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42671. __decorate([
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42674. __decorate([
  42675. BABYLON.serialize("invertNormalMapY")
  42676. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42677. __decorate([
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42679. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42680. __decorate([
  42681. BABYLON.serialize("twoSidedLighting")
  42682. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42683. __decorate([
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42686. __decorate([
  42687. BABYLON.serialize()
  42688. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42689. return StandardMaterial;
  42690. }(BABYLON.PushMaterial));
  42691. BABYLON.StandardMaterial = StandardMaterial;
  42692. })(BABYLON || (BABYLON = {}));
  42693. //# sourceMappingURL=babylon.standardMaterial.js.map
  42694. var BABYLON;
  42695. (function (BABYLON) {
  42696. /**
  42697. * Class representing spherical polynomial coefficients to the 3rd degree
  42698. */
  42699. var SphericalPolynomial = /** @class */ (function () {
  42700. function SphericalPolynomial() {
  42701. /**
  42702. * The x coefficients of the spherical polynomial
  42703. */
  42704. this.x = BABYLON.Vector3.Zero();
  42705. /**
  42706. * The y coefficients of the spherical polynomial
  42707. */
  42708. this.y = BABYLON.Vector3.Zero();
  42709. /**
  42710. * The z coefficients of the spherical polynomial
  42711. */
  42712. this.z = BABYLON.Vector3.Zero();
  42713. /**
  42714. * The xx coefficients of the spherical polynomial
  42715. */
  42716. this.xx = BABYLON.Vector3.Zero();
  42717. /**
  42718. * The yy coefficients of the spherical polynomial
  42719. */
  42720. this.yy = BABYLON.Vector3.Zero();
  42721. /**
  42722. * The zz coefficients of the spherical polynomial
  42723. */
  42724. this.zz = BABYLON.Vector3.Zero();
  42725. /**
  42726. * The xy coefficients of the spherical polynomial
  42727. */
  42728. this.xy = BABYLON.Vector3.Zero();
  42729. /**
  42730. * The yz coefficients of the spherical polynomial
  42731. */
  42732. this.yz = BABYLON.Vector3.Zero();
  42733. /**
  42734. * The zx coefficients of the spherical polynomial
  42735. */
  42736. this.zx = BABYLON.Vector3.Zero();
  42737. }
  42738. /**
  42739. * Adds an ambient color to the spherical polynomial
  42740. * @param color the color to add
  42741. */
  42742. SphericalPolynomial.prototype.addAmbient = function (color) {
  42743. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42744. this.xx = this.xx.add(colorVector);
  42745. this.yy = this.yy.add(colorVector);
  42746. this.zz = this.zz.add(colorVector);
  42747. };
  42748. /**
  42749. * Scales the spherical polynomial by the given amount
  42750. * @param scale the amount to scale
  42751. */
  42752. SphericalPolynomial.prototype.scale = function (scale) {
  42753. this.x = this.x.scale(scale);
  42754. this.y = this.y.scale(scale);
  42755. this.z = this.z.scale(scale);
  42756. this.xx = this.xx.scale(scale);
  42757. this.yy = this.yy.scale(scale);
  42758. this.zz = this.zz.scale(scale);
  42759. this.yz = this.yz.scale(scale);
  42760. this.zx = this.zx.scale(scale);
  42761. this.xy = this.xy.scale(scale);
  42762. };
  42763. /**
  42764. * Gets the spherical polynomial from harmonics
  42765. * @param harmonics the spherical harmonics
  42766. * @returns the spherical polynomial
  42767. */
  42768. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42769. var result = new SphericalPolynomial();
  42770. result.x = harmonics.l11.scale(1.02333);
  42771. result.y = harmonics.l1_1.scale(1.02333);
  42772. result.z = harmonics.l10.scale(1.02333);
  42773. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42774. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42775. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42776. result.yz = harmonics.l2_1.scale(0.858086);
  42777. result.zx = harmonics.l21.scale(0.858086);
  42778. result.xy = harmonics.l2_2.scale(0.858086);
  42779. result.scale(1.0 / Math.PI);
  42780. return result;
  42781. };
  42782. /**
  42783. * Constructs a spherical polynomial from an array.
  42784. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42785. * @returns the spherical polynomial
  42786. */
  42787. SphericalPolynomial.FromArray = function (data) {
  42788. var sp = new SphericalPolynomial();
  42789. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42790. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42791. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42792. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42793. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42794. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42795. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42796. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42797. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  42798. return sp;
  42799. };
  42800. return SphericalPolynomial;
  42801. }());
  42802. BABYLON.SphericalPolynomial = SphericalPolynomial;
  42803. /**
  42804. * Class representing spherical harmonics coefficients to the 3rd degree
  42805. */
  42806. var SphericalHarmonics = /** @class */ (function () {
  42807. function SphericalHarmonics() {
  42808. /**
  42809. * The l0,0 coefficients of the spherical harmonics
  42810. */
  42811. this.l00 = BABYLON.Vector3.Zero();
  42812. /**
  42813. * The l1,-1 coefficients of the spherical harmonics
  42814. */
  42815. this.l1_1 = BABYLON.Vector3.Zero();
  42816. /**
  42817. * The l1,0 coefficients of the spherical harmonics
  42818. */
  42819. this.l10 = BABYLON.Vector3.Zero();
  42820. /**
  42821. * The l1,1 coefficients of the spherical harmonics
  42822. */
  42823. this.l11 = BABYLON.Vector3.Zero();
  42824. /**
  42825. * The l2,-2 coefficients of the spherical harmonics
  42826. */
  42827. this.l2_2 = BABYLON.Vector3.Zero();
  42828. /**
  42829. * The l2,-1 coefficients of the spherical harmonics
  42830. */
  42831. this.l2_1 = BABYLON.Vector3.Zero();
  42832. /**
  42833. * The l2,0 coefficients of the spherical harmonics
  42834. */
  42835. this.l20 = BABYLON.Vector3.Zero();
  42836. /**
  42837. * The l2,1 coefficients of the spherical harmonics
  42838. */
  42839. this.l21 = BABYLON.Vector3.Zero();
  42840. /**
  42841. * The l2,2 coefficients of the spherical harmonics
  42842. */
  42843. this.lL22 = BABYLON.Vector3.Zero();
  42844. }
  42845. /**
  42846. * Adds a light to the spherical harmonics
  42847. * @param direction the direction of the light
  42848. * @param color the color of the light
  42849. * @param deltaSolidAngle the delta solid angle of the light
  42850. */
  42851. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  42852. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42853. var c = colorVector.scale(deltaSolidAngle);
  42854. this.l00 = this.l00.add(c.scale(0.282095));
  42855. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  42856. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  42857. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  42858. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  42859. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  42860. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  42861. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  42862. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  42863. };
  42864. /**
  42865. * Scales the spherical harmonics by the given amount
  42866. * @param scale the amount to scale
  42867. */
  42868. SphericalHarmonics.prototype.scale = function (scale) {
  42869. this.l00 = this.l00.scale(scale);
  42870. this.l1_1 = this.l1_1.scale(scale);
  42871. this.l10 = this.l10.scale(scale);
  42872. this.l11 = this.l11.scale(scale);
  42873. this.l2_2 = this.l2_2.scale(scale);
  42874. this.l2_1 = this.l2_1.scale(scale);
  42875. this.l20 = this.l20.scale(scale);
  42876. this.l21 = this.l21.scale(scale);
  42877. this.lL22 = this.lL22.scale(scale);
  42878. };
  42879. /**
  42880. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  42881. *
  42882. * ```
  42883. * E_lm = A_l * L_lm
  42884. * ```
  42885. *
  42886. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  42887. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  42888. * the scaling factors are given in equation 9.
  42889. */
  42890. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  42891. // Constant (Band 0)
  42892. this.l00 = this.l00.scale(3.141593);
  42893. // Linear (Band 1)
  42894. this.l1_1 = this.l1_1.scale(2.094395);
  42895. this.l10 = this.l10.scale(2.094395);
  42896. this.l11 = this.l11.scale(2.094395);
  42897. // Quadratic (Band 2)
  42898. this.l2_2 = this.l2_2.scale(0.785398);
  42899. this.l2_1 = this.l2_1.scale(0.785398);
  42900. this.l20 = this.l20.scale(0.785398);
  42901. this.l21 = this.l21.scale(0.785398);
  42902. this.lL22 = this.lL22.scale(0.785398);
  42903. };
  42904. /**
  42905. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  42906. *
  42907. * ```
  42908. * L = (1/pi) * E * rho
  42909. * ```
  42910. *
  42911. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  42912. */
  42913. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  42914. this.scale(1.0 / Math.PI);
  42915. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  42916. // (The pixel shader must apply albedo after texture fetches, etc).
  42917. };
  42918. /**
  42919. * Gets the spherical harmonics from polynomial
  42920. * @param polynomial the spherical polynomial
  42921. * @returns the spherical harmonics
  42922. */
  42923. SphericalHarmonics.FromPolynomial = function (polynomial) {
  42924. var result = new SphericalHarmonics();
  42925. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  42926. result.l1_1 = polynomial.y.scale(0.977204);
  42927. result.l10 = polynomial.z.scale(0.977204);
  42928. result.l11 = polynomial.x.scale(0.977204);
  42929. result.l2_2 = polynomial.xy.scale(1.16538);
  42930. result.l2_1 = polynomial.yz.scale(1.16538);
  42931. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  42932. result.l21 = polynomial.zx.scale(1.16538);
  42933. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  42934. result.scale(Math.PI);
  42935. return result;
  42936. };
  42937. /**
  42938. * Constructs a spherical harmonics from an array.
  42939. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  42940. * @returns the spherical harmonics
  42941. */
  42942. SphericalHarmonics.FromArray = function (data) {
  42943. var sh = new SphericalHarmonics();
  42944. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  42945. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  42946. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  42947. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  42948. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  42949. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  42950. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  42951. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  42952. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  42953. return sh;
  42954. };
  42955. return SphericalHarmonics;
  42956. }());
  42957. BABYLON.SphericalHarmonics = SphericalHarmonics;
  42958. })(BABYLON || (BABYLON = {}));
  42959. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  42960. var BABYLON;
  42961. (function (BABYLON) {
  42962. var FileFaceOrientation = /** @class */ (function () {
  42963. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42964. this.name = name;
  42965. this.worldAxisForNormal = worldAxisForNormal;
  42966. this.worldAxisForFileX = worldAxisForFileX;
  42967. this.worldAxisForFileY = worldAxisForFileY;
  42968. }
  42969. return FileFaceOrientation;
  42970. }());
  42971. ;
  42972. /**
  42973. * Helper class dealing with the extraction of spherical polynomial dataArray
  42974. * from a cube map.
  42975. */
  42976. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  42977. function CubeMapToSphericalPolynomialTools() {
  42978. }
  42979. /**
  42980. * Converts a texture to the according Spherical Polynomial data.
  42981. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42982. *
  42983. * @param texture The texture to extract the information from.
  42984. * @return The Spherical Polynomial data.
  42985. */
  42986. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  42987. if (!texture.isCube) {
  42988. // Only supports cube Textures currently.
  42989. return null;
  42990. }
  42991. var size = texture.getSize().width;
  42992. var right = texture.readPixels(0);
  42993. var left = texture.readPixels(1);
  42994. var up;
  42995. var down;
  42996. if (texture.isRenderTarget) {
  42997. up = texture.readPixels(3);
  42998. down = texture.readPixels(2);
  42999. }
  43000. else {
  43001. up = texture.readPixels(2);
  43002. down = texture.readPixels(3);
  43003. }
  43004. var front = texture.readPixels(4);
  43005. var back = texture.readPixels(5);
  43006. var gammaSpace = texture.gammaSpace;
  43007. // Always read as RGBA.
  43008. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43009. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43010. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43011. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43012. }
  43013. var cubeInfo = {
  43014. size: size,
  43015. right: right,
  43016. left: left,
  43017. up: up,
  43018. down: down,
  43019. front: front,
  43020. back: back,
  43021. format: format,
  43022. type: type,
  43023. gammaSpace: gammaSpace,
  43024. };
  43025. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43026. };
  43027. /**
  43028. * Converts a cubemap to the according Spherical Polynomial data.
  43029. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43030. *
  43031. * @param cubeInfo The Cube map to extract the information from.
  43032. * @return The Spherical Polynomial data.
  43033. */
  43034. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43035. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43036. var totalSolidAngle = 0.0;
  43037. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43038. var du = 2.0 / cubeInfo.size;
  43039. var dv = du;
  43040. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43041. var minUV = du * 0.5 - 1.0;
  43042. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43043. var fileFace = this.FileFaces[faceIndex];
  43044. var dataArray = cubeInfo[fileFace.name];
  43045. var v = minUV;
  43046. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43047. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43048. // Because SP is still linear, so summation is fine in that basis.
  43049. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43050. for (var y = 0; y < cubeInfo.size; y++) {
  43051. var u = minUV;
  43052. for (var x = 0; x < cubeInfo.size; x++) {
  43053. // World direction (not normalised)
  43054. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43055. worldDirection.normalize();
  43056. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43057. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43058. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43059. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43060. // Handle Integer types.
  43061. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43062. r /= 255;
  43063. g /= 255;
  43064. b /= 255;
  43065. }
  43066. // Handle Gamma space textures.
  43067. if (cubeInfo.gammaSpace) {
  43068. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43069. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43070. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43071. }
  43072. var color = new BABYLON.Color3(r, g, b);
  43073. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43074. totalSolidAngle += deltaSolidAngle;
  43075. u += du;
  43076. }
  43077. v += dv;
  43078. }
  43079. }
  43080. // Solid angle for entire sphere is 4*pi
  43081. var sphereSolidAngle = 4.0 * Math.PI;
  43082. // Adjust the solid angle to allow for how many faces we processed.
  43083. var facesProcessed = 6.0;
  43084. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43085. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43086. // This is needed because the numerical integration over the cube uses a
  43087. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43088. // and also to compensate for accumulative error due to float precision in the summation.
  43089. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43090. sphericalHarmonics.scale(correctionFactor);
  43091. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43092. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43093. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43094. };
  43095. CubeMapToSphericalPolynomialTools.FileFaces = [
  43096. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43097. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43098. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43099. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43100. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43101. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43102. ];
  43103. return CubeMapToSphericalPolynomialTools;
  43104. }());
  43105. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43106. })(BABYLON || (BABYLON = {}));
  43107. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43108. var BABYLON;
  43109. (function (BABYLON) {
  43110. /**
  43111. * Manages the defines for the PBR Material.
  43112. * @hiddenChildren
  43113. */
  43114. var PBRMaterialDefines = /** @class */ (function (_super) {
  43115. __extends(PBRMaterialDefines, _super);
  43116. /**
  43117. * Initializes the PBR Material defines.
  43118. */
  43119. function PBRMaterialDefines() {
  43120. var _this = _super.call(this) || this;
  43121. _this.PBR = true;
  43122. _this.MAINUV1 = false;
  43123. _this.MAINUV2 = false;
  43124. _this.UV1 = false;
  43125. _this.UV2 = false;
  43126. _this.ALBEDO = false;
  43127. _this.ALBEDODIRECTUV = 0;
  43128. _this.VERTEXCOLOR = false;
  43129. _this.AMBIENT = false;
  43130. _this.AMBIENTDIRECTUV = 0;
  43131. _this.AMBIENTINGRAYSCALE = false;
  43132. _this.OPACITY = false;
  43133. _this.VERTEXALPHA = false;
  43134. _this.OPACITYDIRECTUV = 0;
  43135. _this.OPACITYRGB = false;
  43136. _this.ALPHATEST = false;
  43137. _this.DEPTHPREPASS = false;
  43138. _this.ALPHABLEND = false;
  43139. _this.ALPHAFROMALBEDO = false;
  43140. _this.ALPHATESTVALUE = "0.5";
  43141. _this.SPECULAROVERALPHA = false;
  43142. _this.RADIANCEOVERALPHA = false;
  43143. _this.ALPHAFRESNEL = false;
  43144. _this.LINEARALPHAFRESNEL = false;
  43145. _this.PREMULTIPLYALPHA = false;
  43146. _this.EMISSIVE = false;
  43147. _this.EMISSIVEDIRECTUV = 0;
  43148. _this.REFLECTIVITY = false;
  43149. _this.REFLECTIVITYDIRECTUV = 0;
  43150. _this.SPECULARTERM = false;
  43151. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43152. _this.MICROSURFACEAUTOMATIC = false;
  43153. _this.LODBASEDMICROSFURACE = false;
  43154. _this.MICROSURFACEMAP = false;
  43155. _this.MICROSURFACEMAPDIRECTUV = 0;
  43156. _this.METALLICWORKFLOW = false;
  43157. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43158. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43159. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43160. _this.AOSTOREINMETALMAPRED = false;
  43161. _this.ENVIRONMENTBRDF = false;
  43162. _this.NORMAL = false;
  43163. _this.TANGENT = false;
  43164. _this.BUMP = false;
  43165. _this.BUMPDIRECTUV = 0;
  43166. _this.OBJECTSPACE_NORMALMAP = false;
  43167. _this.PARALLAX = false;
  43168. _this.PARALLAXOCCLUSION = false;
  43169. _this.NORMALXYSCALE = true;
  43170. _this.LIGHTMAP = false;
  43171. _this.LIGHTMAPDIRECTUV = 0;
  43172. _this.USELIGHTMAPASSHADOWMAP = false;
  43173. _this.GAMMALIGHTMAP = false;
  43174. _this.REFLECTION = false;
  43175. _this.REFLECTIONMAP_3D = false;
  43176. _this.REFLECTIONMAP_SPHERICAL = false;
  43177. _this.REFLECTIONMAP_PLANAR = false;
  43178. _this.REFLECTIONMAP_CUBIC = false;
  43179. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43180. _this.REFLECTIONMAP_PROJECTION = false;
  43181. _this.REFLECTIONMAP_SKYBOX = false;
  43182. _this.REFLECTIONMAP_EXPLICIT = false;
  43183. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43184. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43185. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43186. _this.INVERTCUBICMAP = false;
  43187. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43188. _this.USESPHERICALINVERTEX = false;
  43189. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43190. _this.LODINREFLECTIONALPHA = false;
  43191. _this.GAMMAREFLECTION = false;
  43192. _this.RGBDREFLECTION = false;
  43193. _this.RADIANCEOCCLUSION = false;
  43194. _this.HORIZONOCCLUSION = false;
  43195. _this.REFRACTION = false;
  43196. _this.REFRACTIONMAP_3D = false;
  43197. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43198. _this.LODINREFRACTIONALPHA = false;
  43199. _this.GAMMAREFRACTION = false;
  43200. _this.RGBDREFRACTION = false;
  43201. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43202. _this.INSTANCES = false;
  43203. _this.NUM_BONE_INFLUENCERS = 0;
  43204. _this.BonesPerMesh = 0;
  43205. _this.NONUNIFORMSCALING = false;
  43206. _this.MORPHTARGETS = false;
  43207. _this.MORPHTARGETS_NORMAL = false;
  43208. _this.MORPHTARGETS_TANGENT = false;
  43209. _this.NUM_MORPH_INFLUENCERS = 0;
  43210. _this.IMAGEPROCESSING = false;
  43211. _this.VIGNETTE = false;
  43212. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43213. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43214. _this.TONEMAPPING = false;
  43215. _this.CONTRAST = false;
  43216. _this.COLORCURVES = false;
  43217. _this.COLORGRADING = false;
  43218. _this.COLORGRADING3D = false;
  43219. _this.SAMPLER3DGREENDEPTH = false;
  43220. _this.SAMPLER3DBGRMAP = false;
  43221. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43222. _this.EXPOSURE = false;
  43223. _this.USEPHYSICALLIGHTFALLOFF = false;
  43224. _this.TWOSIDEDLIGHTING = false;
  43225. _this.SHADOWFLOAT = false;
  43226. _this.CLIPPLANE = false;
  43227. _this.POINTSIZE = false;
  43228. _this.FOG = false;
  43229. _this.LOGARITHMICDEPTH = false;
  43230. _this.FORCENORMALFORWARD = false;
  43231. _this.SPECULARAA = false;
  43232. _this.UNLIT = false;
  43233. _this.rebuild();
  43234. return _this;
  43235. }
  43236. /**
  43237. * Resets the PBR Material defines.
  43238. */
  43239. PBRMaterialDefines.prototype.reset = function () {
  43240. _super.prototype.reset.call(this);
  43241. this.ALPHATESTVALUE = "0.5";
  43242. this.PBR = true;
  43243. };
  43244. return PBRMaterialDefines;
  43245. }(BABYLON.MaterialDefines));
  43246. /**
  43247. * The Physically based material base class of BJS.
  43248. *
  43249. * This offers the main features of a standard PBR material.
  43250. * For more information, please refer to the documentation :
  43251. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43252. */
  43253. var PBRBaseMaterial = /** @class */ (function (_super) {
  43254. __extends(PBRBaseMaterial, _super);
  43255. /**
  43256. * Instantiates a new PBRMaterial instance.
  43257. *
  43258. * @param name The material name
  43259. * @param scene The scene the material will be use in.
  43260. */
  43261. function PBRBaseMaterial(name, scene) {
  43262. var _this = _super.call(this, name, scene) || this;
  43263. /**
  43264. * Intensity of the direct lights e.g. the four lights available in your scene.
  43265. * This impacts both the direct diffuse and specular highlights.
  43266. */
  43267. _this._directIntensity = 1.0;
  43268. /**
  43269. * Intensity of the emissive part of the material.
  43270. * This helps controlling the emissive effect without modifying the emissive color.
  43271. */
  43272. _this._emissiveIntensity = 1.0;
  43273. /**
  43274. * Intensity of the environment e.g. how much the environment will light the object
  43275. * either through harmonics for rough material or through the refelction for shiny ones.
  43276. */
  43277. _this._environmentIntensity = 1.0;
  43278. /**
  43279. * This is a special control allowing the reduction of the specular highlights coming from the
  43280. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43281. */
  43282. _this._specularIntensity = 1.0;
  43283. /**
  43284. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43285. */
  43286. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43287. /**
  43288. * Debug Control allowing disabling the bump map on this material.
  43289. */
  43290. _this._disableBumpMap = false;
  43291. /**
  43292. * AKA Occlusion Texture Intensity in other nomenclature.
  43293. */
  43294. _this._ambientTextureStrength = 1.0;
  43295. /**
  43296. * The color of a material in ambient lighting.
  43297. */
  43298. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43299. /**
  43300. * AKA Diffuse Color in other nomenclature.
  43301. */
  43302. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43303. /**
  43304. * AKA Specular Color in other nomenclature.
  43305. */
  43306. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43307. /**
  43308. * The color applied when light is reflected from a material.
  43309. */
  43310. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43311. /**
  43312. * The color applied when light is emitted from a material.
  43313. */
  43314. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43315. /**
  43316. * AKA Glossiness in other nomenclature.
  43317. */
  43318. _this._microSurface = 0.9;
  43319. /**
  43320. * source material index of refraction (IOR)' / 'destination material IOR.
  43321. */
  43322. _this._indexOfRefraction = 0.66;
  43323. /**
  43324. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43325. */
  43326. _this._invertRefractionY = false;
  43327. /**
  43328. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43329. * Materials half opaque for instance using refraction could benefit from this control.
  43330. */
  43331. _this._linkRefractionWithTransparency = false;
  43332. /**
  43333. * Specifies that the material will use the light map as a show map.
  43334. */
  43335. _this._useLightmapAsShadowmap = false;
  43336. /**
  43337. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43338. * makes the reflect vector face the model (under horizon).
  43339. */
  43340. _this._useHorizonOcclusion = true;
  43341. /**
  43342. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43343. * too much the area relying on ambient texture to define their ambient occlusion.
  43344. */
  43345. _this._useRadianceOcclusion = true;
  43346. /**
  43347. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43348. */
  43349. _this._useAlphaFromAlbedoTexture = false;
  43350. /**
  43351. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43352. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43353. */
  43354. _this._useSpecularOverAlpha = true;
  43355. /**
  43356. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43357. */
  43358. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43359. /**
  43360. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43361. */
  43362. _this._useRoughnessFromMetallicTextureAlpha = true;
  43363. /**
  43364. * Specifies if the metallic texture contains the roughness information in its green channel.
  43365. */
  43366. _this._useRoughnessFromMetallicTextureGreen = false;
  43367. /**
  43368. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43369. */
  43370. _this._useMetallnessFromMetallicTextureBlue = false;
  43371. /**
  43372. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43373. */
  43374. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43375. /**
  43376. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43377. */
  43378. _this._useAmbientInGrayScale = false;
  43379. /**
  43380. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43381. * The material will try to infer what glossiness each pixel should be.
  43382. */
  43383. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43384. /**
  43385. * BJS is using an harcoded light falloff based on a manually sets up range.
  43386. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43387. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43388. */
  43389. _this._usePhysicalLightFalloff = true;
  43390. /**
  43391. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43392. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43393. */
  43394. _this._useRadianceOverAlpha = true;
  43395. /**
  43396. * Allows using an object space normal map (instead of tangent space).
  43397. */
  43398. _this._useObjectSpaceNormalMap = false;
  43399. /**
  43400. * Allows using the bump map in parallax mode.
  43401. */
  43402. _this._useParallax = false;
  43403. /**
  43404. * Allows using the bump map in parallax occlusion mode.
  43405. */
  43406. _this._useParallaxOcclusion = false;
  43407. /**
  43408. * Controls the scale bias of the parallax mode.
  43409. */
  43410. _this._parallaxScaleBias = 0.05;
  43411. /**
  43412. * If sets to true, disables all the lights affecting the material.
  43413. */
  43414. _this._disableLighting = false;
  43415. /**
  43416. * Number of Simultaneous lights allowed on the material.
  43417. */
  43418. _this._maxSimultaneousLights = 4;
  43419. /**
  43420. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43421. */
  43422. _this._invertNormalMapX = false;
  43423. /**
  43424. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43425. */
  43426. _this._invertNormalMapY = false;
  43427. /**
  43428. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43429. */
  43430. _this._twoSidedLighting = false;
  43431. /**
  43432. * Defines the alpha limits in alpha test mode.
  43433. */
  43434. _this._alphaCutOff = 0.4;
  43435. /**
  43436. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43437. */
  43438. _this._forceAlphaTest = false;
  43439. /**
  43440. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43441. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43442. */
  43443. _this._useAlphaFresnel = false;
  43444. /**
  43445. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43446. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43447. */
  43448. _this._useLinearAlphaFresnel = false;
  43449. /**
  43450. * The transparency mode of the material.
  43451. */
  43452. _this._transparencyMode = null;
  43453. /**
  43454. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43455. * from cos thetav and roughness:
  43456. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43457. */
  43458. _this._environmentBRDFTexture = null;
  43459. /**
  43460. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43461. */
  43462. _this._forceIrradianceInFragment = false;
  43463. /**
  43464. * Force normal to face away from face.
  43465. */
  43466. _this._forceNormalForward = false;
  43467. /**
  43468. * Enables specular anti aliasing in the PBR shader.
  43469. * It will both interacts on the Geometry for analytical and IBL lighting.
  43470. * It also prefilter the roughness map based on the bump values.
  43471. */
  43472. _this._enableSpecularAntiAliasing = false;
  43473. /**
  43474. * Stores the available render targets.
  43475. */
  43476. _this._renderTargets = new BABYLON.SmartArray(16);
  43477. /**
  43478. * Sets the global ambient color for the material used in lighting calculations.
  43479. */
  43480. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43481. /**
  43482. * If set to true, no lighting calculations will be applied.
  43483. */
  43484. _this._unlit = false;
  43485. // Setup the default processing configuration to the scene.
  43486. _this._attachImageProcessingConfiguration(null);
  43487. _this.getRenderTargetTextures = function () {
  43488. _this._renderTargets.reset();
  43489. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43490. _this._renderTargets.push(_this._reflectionTexture);
  43491. }
  43492. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43493. _this._renderTargets.push(_this._refractionTexture);
  43494. }
  43495. return _this._renderTargets;
  43496. };
  43497. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43498. return _this;
  43499. }
  43500. /**
  43501. * Attaches a new image processing configuration to the PBR Material.
  43502. * @param configuration
  43503. */
  43504. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43505. var _this = this;
  43506. if (configuration === this._imageProcessingConfiguration) {
  43507. return;
  43508. }
  43509. // Detaches observer.
  43510. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43511. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43512. }
  43513. // Pick the scene configuration if needed.
  43514. if (!configuration) {
  43515. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43516. }
  43517. else {
  43518. this._imageProcessingConfiguration = configuration;
  43519. }
  43520. // Attaches observer.
  43521. if (this._imageProcessingConfiguration) {
  43522. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43523. _this._markAllSubMeshesAsImageProcessingDirty();
  43524. });
  43525. }
  43526. };
  43527. /**
  43528. * Gets the name of the material class.
  43529. */
  43530. PBRBaseMaterial.prototype.getClassName = function () {
  43531. return "PBRBaseMaterial";
  43532. };
  43533. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43534. /**
  43535. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43536. */
  43537. get: function () {
  43538. return this._useLogarithmicDepth;
  43539. },
  43540. /**
  43541. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43542. */
  43543. set: function (value) {
  43544. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43545. },
  43546. enumerable: true,
  43547. configurable: true
  43548. });
  43549. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43550. /**
  43551. * Gets the current transparency mode.
  43552. */
  43553. get: function () {
  43554. return this._transparencyMode;
  43555. },
  43556. /**
  43557. * Sets the transparency mode of the material.
  43558. *
  43559. * | Value | Type | Description |
  43560. * | ----- | ----------------------------------- | ----------- |
  43561. * | 0 | OPAQUE | |
  43562. * | 1 | ALPHATEST | |
  43563. * | 2 | ALPHABLEND | |
  43564. * | 3 | ALPHATESTANDBLEND | |
  43565. *
  43566. */
  43567. set: function (value) {
  43568. if (this._transparencyMode === value) {
  43569. return;
  43570. }
  43571. this._transparencyMode = value;
  43572. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43573. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43574. },
  43575. enumerable: true,
  43576. configurable: true
  43577. });
  43578. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43579. /**
  43580. * Returns true if alpha blending should be disabled.
  43581. */
  43582. get: function () {
  43583. return (this._linkRefractionWithTransparency ||
  43584. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43585. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43586. },
  43587. enumerable: true,
  43588. configurable: true
  43589. });
  43590. /**
  43591. * Specifies whether or not this material should be rendered in alpha blend mode.
  43592. */
  43593. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43594. if (this._disableAlphaBlending) {
  43595. return false;
  43596. }
  43597. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43598. };
  43599. /**
  43600. * Specifies if the mesh will require alpha blending.
  43601. * @param mesh - BJS mesh.
  43602. */
  43603. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43604. if (this._disableAlphaBlending) {
  43605. return false;
  43606. }
  43607. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43608. };
  43609. /**
  43610. * Specifies whether or not this material should be rendered in alpha test mode.
  43611. */
  43612. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43613. if (this._forceAlphaTest) {
  43614. return true;
  43615. }
  43616. if (this._linkRefractionWithTransparency) {
  43617. return false;
  43618. }
  43619. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43620. };
  43621. /**
  43622. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43623. */
  43624. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43625. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43626. };
  43627. /**
  43628. * Gets the texture used for the alpha test.
  43629. */
  43630. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43631. return this._albedoTexture;
  43632. };
  43633. /**
  43634. * Specifies that the submesh is ready to be used.
  43635. * @param mesh - BJS mesh.
  43636. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43637. * @param useInstances - Specifies that instances should be used.
  43638. * @returns - boolean indicating that the submesh is ready or not.
  43639. */
  43640. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43641. if (subMesh.effect && this.isFrozen) {
  43642. if (this._wasPreviouslyReady) {
  43643. return true;
  43644. }
  43645. }
  43646. if (!subMesh._materialDefines) {
  43647. subMesh._materialDefines = new PBRMaterialDefines();
  43648. }
  43649. var defines = subMesh._materialDefines;
  43650. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43651. if (defines._renderId === this.getScene().getRenderId()) {
  43652. return true;
  43653. }
  43654. }
  43655. var scene = this.getScene();
  43656. var engine = scene.getEngine();
  43657. if (defines._areTexturesDirty) {
  43658. if (scene.texturesEnabled) {
  43659. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43660. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43661. return false;
  43662. }
  43663. }
  43664. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43665. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43666. return false;
  43667. }
  43668. }
  43669. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43670. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43671. return false;
  43672. }
  43673. }
  43674. var reflectionTexture = this._getReflectionTexture();
  43675. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43676. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43677. return false;
  43678. }
  43679. }
  43680. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43681. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43682. return false;
  43683. }
  43684. }
  43685. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43686. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43687. return false;
  43688. }
  43689. }
  43690. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43691. if (this._metallicTexture) {
  43692. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43693. return false;
  43694. }
  43695. }
  43696. else if (this._reflectivityTexture) {
  43697. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43698. return false;
  43699. }
  43700. }
  43701. if (this._microSurfaceTexture) {
  43702. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43703. return false;
  43704. }
  43705. }
  43706. }
  43707. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43708. // Bump texture cannot be not blocking.
  43709. if (!this._bumpTexture.isReady()) {
  43710. return false;
  43711. }
  43712. }
  43713. var refractionTexture = this._getRefractionTexture();
  43714. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43715. if (!refractionTexture.isReadyOrNotBlocking()) {
  43716. return false;
  43717. }
  43718. }
  43719. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43720. // This is blocking.
  43721. if (!this._environmentBRDFTexture.isReady()) {
  43722. return false;
  43723. }
  43724. }
  43725. }
  43726. }
  43727. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43728. if (!this._imageProcessingConfiguration.isReady()) {
  43729. return false;
  43730. }
  43731. }
  43732. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43733. mesh.createNormals(true);
  43734. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43735. }
  43736. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43737. if (effect) {
  43738. scene.resetCachedMaterial();
  43739. subMesh.setEffect(effect, defines);
  43740. this.buildUniformLayout();
  43741. }
  43742. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43743. return false;
  43744. }
  43745. defines._renderId = scene.getRenderId();
  43746. this._wasPreviouslyReady = true;
  43747. return true;
  43748. };
  43749. /**
  43750. * Specifies if the material uses metallic roughness workflow.
  43751. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43752. */
  43753. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43754. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43755. return true;
  43756. }
  43757. return false;
  43758. };
  43759. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43760. if (onCompiled === void 0) { onCompiled = null; }
  43761. if (onError === void 0) { onError = null; }
  43762. if (useInstances === void 0) { useInstances = null; }
  43763. if (useClipPlane === void 0) { useClipPlane = null; }
  43764. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43765. if (!defines.isDirty) {
  43766. return null;
  43767. }
  43768. defines.markAsProcessed();
  43769. var scene = this.getScene();
  43770. var engine = scene.getEngine();
  43771. // Fallbacks
  43772. var fallbacks = new BABYLON.EffectFallbacks();
  43773. var fallbackRank = 0;
  43774. if (defines.USESPHERICALINVERTEX) {
  43775. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43776. }
  43777. if (defines.FOG) {
  43778. fallbacks.addFallback(fallbackRank, "FOG");
  43779. }
  43780. if (defines.SPECULARAA) {
  43781. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43782. }
  43783. if (defines.POINTSIZE) {
  43784. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43785. }
  43786. if (defines.LOGARITHMICDEPTH) {
  43787. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43788. }
  43789. if (defines.PARALLAX) {
  43790. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43791. }
  43792. if (defines.PARALLAXOCCLUSION) {
  43793. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43794. }
  43795. if (defines.ENVIRONMENTBRDF) {
  43796. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43797. }
  43798. if (defines.TANGENT) {
  43799. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43800. }
  43801. if (defines.BUMP) {
  43802. fallbacks.addFallback(fallbackRank++, "BUMP");
  43803. }
  43804. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43805. if (defines.SPECULARTERM) {
  43806. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43807. }
  43808. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43809. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43810. }
  43811. if (defines.LIGHTMAP) {
  43812. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43813. }
  43814. if (defines.NORMAL) {
  43815. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43816. }
  43817. if (defines.AMBIENT) {
  43818. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43819. }
  43820. if (defines.EMISSIVE) {
  43821. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43822. }
  43823. if (defines.VERTEXCOLOR) {
  43824. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43825. }
  43826. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43827. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43828. }
  43829. if (defines.MORPHTARGETS) {
  43830. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43831. }
  43832. //Attributes
  43833. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43834. if (defines.NORMAL) {
  43835. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43836. }
  43837. if (defines.TANGENT) {
  43838. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43839. }
  43840. if (defines.UV1) {
  43841. attribs.push(BABYLON.VertexBuffer.UVKind);
  43842. }
  43843. if (defines.UV2) {
  43844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43845. }
  43846. if (defines.VERTEXCOLOR) {
  43847. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43848. }
  43849. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43850. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43851. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43852. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43853. "vFogInfos", "vFogColor", "pointSize",
  43854. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43855. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43856. "mBones",
  43857. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43858. "vLightingIntensity",
  43859. "logarithmicDepthConstant",
  43860. "vSphericalX", "vSphericalY", "vSphericalZ",
  43861. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43862. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43863. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43864. "vTangentSpaceParams"
  43865. ];
  43866. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  43867. "bumpSampler", "lightmapSampler", "opacitySampler",
  43868. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  43869. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  43870. "microSurfaceSampler", "environmentBrdfSampler"];
  43871. var uniformBuffers = ["Material", "Scene"];
  43872. if (BABYLON.ImageProcessingConfiguration) {
  43873. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43874. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43875. }
  43876. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43877. uniformsNames: uniforms,
  43878. uniformBuffersNames: uniformBuffers,
  43879. samplers: samplers,
  43880. defines: defines,
  43881. maxSimultaneousLights: this._maxSimultaneousLights
  43882. });
  43883. var join = defines.toString();
  43884. return engine.createEffect("pbr", {
  43885. attributes: attribs,
  43886. uniformsNames: uniforms,
  43887. uniformBuffersNames: uniformBuffers,
  43888. samplers: samplers,
  43889. defines: join,
  43890. fallbacks: fallbacks,
  43891. onCompiled: onCompiled,
  43892. onError: onError,
  43893. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43894. }, engine);
  43895. };
  43896. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  43897. if (useInstances === void 0) { useInstances = null; }
  43898. if (useClipPlane === void 0) { useClipPlane = null; }
  43899. var scene = this.getScene();
  43900. var engine = scene.getEngine();
  43901. // Lights
  43902. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43903. defines._needNormals = true;
  43904. // Textures
  43905. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  43906. if (defines._areTexturesDirty) {
  43907. defines._needUVs = false;
  43908. if (scene.texturesEnabled) {
  43909. if (scene.getEngine().getCaps().textureLOD) {
  43910. defines.LODBASEDMICROSFURACE = true;
  43911. }
  43912. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43913. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  43914. }
  43915. else {
  43916. defines.ALBEDO = false;
  43917. }
  43918. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43919. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43920. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  43921. }
  43922. else {
  43923. defines.AMBIENT = false;
  43924. }
  43925. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43926. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43927. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43928. }
  43929. else {
  43930. defines.OPACITY = false;
  43931. }
  43932. var reflectionTexture = this._getReflectionTexture();
  43933. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43934. defines.REFLECTION = true;
  43935. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  43936. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  43937. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  43938. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  43939. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  43940. defines.INVERTCUBICMAP = true;
  43941. }
  43942. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  43943. switch (reflectionTexture.coordinatesMode) {
  43944. case BABYLON.Texture.EXPLICIT_MODE:
  43945. defines.REFLECTIONMAP_EXPLICIT = true;
  43946. break;
  43947. case BABYLON.Texture.PLANAR_MODE:
  43948. defines.REFLECTIONMAP_PLANAR = true;
  43949. break;
  43950. case BABYLON.Texture.PROJECTION_MODE:
  43951. defines.REFLECTIONMAP_PROJECTION = true;
  43952. break;
  43953. case BABYLON.Texture.SKYBOX_MODE:
  43954. defines.REFLECTIONMAP_SKYBOX = true;
  43955. break;
  43956. case BABYLON.Texture.SPHERICAL_MODE:
  43957. defines.REFLECTIONMAP_SPHERICAL = true;
  43958. break;
  43959. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43960. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  43961. break;
  43962. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43963. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  43964. break;
  43965. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43966. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  43967. break;
  43968. case BABYLON.Texture.CUBIC_MODE:
  43969. case BABYLON.Texture.INVCUBIC_MODE:
  43970. default:
  43971. defines.REFLECTIONMAP_CUBIC = true;
  43972. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  43973. break;
  43974. }
  43975. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  43976. if (reflectionTexture.sphericalPolynomial) {
  43977. defines.USESPHERICALFROMREFLECTIONMAP = true;
  43978. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  43979. defines.USESPHERICALINVERTEX = false;
  43980. }
  43981. else {
  43982. defines.USESPHERICALINVERTEX = true;
  43983. }
  43984. }
  43985. }
  43986. }
  43987. else {
  43988. defines.REFLECTION = false;
  43989. defines.REFLECTIONMAP_3D = false;
  43990. defines.REFLECTIONMAP_SPHERICAL = false;
  43991. defines.REFLECTIONMAP_PLANAR = false;
  43992. defines.REFLECTIONMAP_CUBIC = false;
  43993. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43994. defines.REFLECTIONMAP_PROJECTION = false;
  43995. defines.REFLECTIONMAP_SKYBOX = false;
  43996. defines.REFLECTIONMAP_EXPLICIT = false;
  43997. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43998. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43999. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44000. defines.INVERTCUBICMAP = false;
  44001. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44002. defines.USESPHERICALINVERTEX = false;
  44003. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44004. defines.LODINREFLECTIONALPHA = false;
  44005. defines.GAMMAREFLECTION = false;
  44006. defines.RGBDREFLECTION = false;
  44007. }
  44008. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44009. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44010. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44011. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44012. }
  44013. else {
  44014. defines.LIGHTMAP = false;
  44015. }
  44016. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44017. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44018. }
  44019. else {
  44020. defines.EMISSIVE = false;
  44021. }
  44022. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44023. if (this._metallicTexture) {
  44024. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44025. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44026. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44027. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44028. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44029. }
  44030. else if (this._reflectivityTexture) {
  44031. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44032. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44033. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44034. }
  44035. else {
  44036. defines.REFLECTIVITY = false;
  44037. }
  44038. if (this._microSurfaceTexture) {
  44039. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44040. }
  44041. else {
  44042. defines.MICROSURFACEMAP = false;
  44043. }
  44044. }
  44045. else {
  44046. defines.REFLECTIVITY = false;
  44047. defines.MICROSURFACEMAP = false;
  44048. }
  44049. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44050. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44051. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44052. defines.PARALLAX = true;
  44053. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44054. }
  44055. else {
  44056. defines.PARALLAX = false;
  44057. }
  44058. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44059. }
  44060. else {
  44061. defines.BUMP = false;
  44062. }
  44063. var refractionTexture = this._getRefractionTexture();
  44064. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44065. defines.REFRACTION = true;
  44066. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44067. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44068. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44069. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44070. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44071. if (this._linkRefractionWithTransparency) {
  44072. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44073. }
  44074. }
  44075. else {
  44076. defines.REFRACTION = false;
  44077. }
  44078. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44079. defines.ENVIRONMENTBRDF = true;
  44080. }
  44081. else {
  44082. defines.ENVIRONMENTBRDF = false;
  44083. }
  44084. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44085. defines.ALPHAFROMALBEDO = true;
  44086. }
  44087. else {
  44088. defines.ALPHAFROMALBEDO = false;
  44089. }
  44090. }
  44091. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44092. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44093. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44094. if (!this.backFaceCulling && this._twoSidedLighting) {
  44095. defines.TWOSIDEDLIGHTING = true;
  44096. }
  44097. else {
  44098. defines.TWOSIDEDLIGHTING = false;
  44099. }
  44100. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44101. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44102. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44103. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44104. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44105. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44106. }
  44107. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44108. this._imageProcessingConfiguration.prepareDefines(defines);
  44109. }
  44110. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44111. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44112. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44113. // Misc.
  44114. if (defines._areMiscDirty) {
  44115. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44116. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44117. }
  44118. // Values that need to be evaluated on every frame
  44119. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44120. // Attribs
  44121. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44122. };
  44123. /**
  44124. * Force shader compilation
  44125. */
  44126. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44127. var _this = this;
  44128. var localOptions = __assign({ clipPlane: false }, options);
  44129. var defines = new PBRMaterialDefines();
  44130. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44131. if (effect.isReady()) {
  44132. if (onCompiled) {
  44133. onCompiled(this);
  44134. }
  44135. }
  44136. else {
  44137. effect.onCompileObservable.add(function () {
  44138. if (onCompiled) {
  44139. onCompiled(_this);
  44140. }
  44141. });
  44142. }
  44143. };
  44144. /**
  44145. * Initializes the uniform buffer layout for the shader.
  44146. */
  44147. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44148. // Order is important !
  44149. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44150. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44151. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44152. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44153. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44154. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44155. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44156. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44157. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44158. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44159. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44160. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44161. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44162. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44163. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44164. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44165. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44166. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44167. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44168. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44169. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44170. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44171. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44172. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44173. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44174. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44175. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44176. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44177. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44178. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44179. this._uniformBuffer.addUniform("pointSize", 1);
  44180. this._uniformBuffer.create();
  44181. };
  44182. /**
  44183. * Unbinds the textures.
  44184. */
  44185. PBRBaseMaterial.prototype.unbind = function () {
  44186. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44187. this._uniformBuffer.setTexture("reflectionSampler", null);
  44188. }
  44189. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44190. this._uniformBuffer.setTexture("refractionSampler", null);
  44191. }
  44192. _super.prototype.unbind.call(this);
  44193. };
  44194. /**
  44195. * Binds the submesh data.
  44196. * @param world - The world matrix.
  44197. * @param mesh - The BJS mesh.
  44198. * @param subMesh - A submesh of the BJS mesh.
  44199. */
  44200. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44201. var scene = this.getScene();
  44202. var defines = subMesh._materialDefines;
  44203. if (!defines) {
  44204. return;
  44205. }
  44206. var effect = subMesh.effect;
  44207. if (!effect) {
  44208. return;
  44209. }
  44210. this._activeEffect = effect;
  44211. // Matrices
  44212. this.bindOnlyWorldMatrix(world);
  44213. // Normal Matrix
  44214. if (defines.OBJECTSPACE_NORMALMAP) {
  44215. world.toNormalMatrix(this._normalMatrix);
  44216. this.bindOnlyNormalMatrix(this._normalMatrix);
  44217. }
  44218. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44219. // Bones
  44220. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44221. var reflectionTexture = null;
  44222. if (mustRebind) {
  44223. this._uniformBuffer.bindToEffect(effect, "Material");
  44224. this.bindViewProjection(effect);
  44225. reflectionTexture = this._getReflectionTexture();
  44226. var refractionTexture = this._getRefractionTexture();
  44227. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44228. // Texture uniforms
  44229. if (scene.texturesEnabled) {
  44230. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44231. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44232. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44233. }
  44234. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44235. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44236. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44237. }
  44238. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44239. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44240. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44241. }
  44242. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44243. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44244. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44245. if (reflectionTexture.boundingBoxSize) {
  44246. var cubeTexture = reflectionTexture;
  44247. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44248. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44249. }
  44250. var polynomials = reflectionTexture.sphericalPolynomial;
  44251. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44252. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44253. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44254. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44255. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44256. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44257. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44258. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44259. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44260. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44261. }
  44262. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44263. }
  44264. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44265. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44266. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44267. }
  44268. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44269. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44270. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44271. }
  44272. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44273. if (this._metallicTexture) {
  44274. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44275. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44276. }
  44277. else if (this._reflectivityTexture) {
  44278. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44279. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44280. }
  44281. if (this._microSurfaceTexture) {
  44282. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44283. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44284. }
  44285. }
  44286. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44287. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44288. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44289. if (scene._mirroredCameraPosition) {
  44290. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44291. }
  44292. else {
  44293. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44294. }
  44295. }
  44296. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44297. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44298. var depth = 1.0;
  44299. if (!refractionTexture.isCube) {
  44300. if (refractionTexture.depth) {
  44301. depth = refractionTexture.depth;
  44302. }
  44303. }
  44304. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44305. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44306. }
  44307. }
  44308. // Point size
  44309. if (this.pointsCloud) {
  44310. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44311. }
  44312. // Colors
  44313. if (defines.METALLICWORKFLOW) {
  44314. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44315. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44316. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44317. }
  44318. else {
  44319. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44320. }
  44321. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44322. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44323. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44324. // Misc
  44325. this._lightingInfos.x = this._directIntensity;
  44326. this._lightingInfos.y = this._emissiveIntensity;
  44327. this._lightingInfos.z = this._environmentIntensity;
  44328. this._lightingInfos.w = this._specularIntensity;
  44329. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44330. }
  44331. // Textures
  44332. if (scene.texturesEnabled) {
  44333. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44334. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44335. }
  44336. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44337. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44338. }
  44339. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44340. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44341. }
  44342. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44343. if (defines.LODBASEDMICROSFURACE) {
  44344. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44345. }
  44346. else {
  44347. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44348. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44349. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44350. }
  44351. }
  44352. if (defines.ENVIRONMENTBRDF) {
  44353. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44354. }
  44355. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44356. if (defines.LODBASEDMICROSFURACE) {
  44357. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44358. }
  44359. else {
  44360. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44361. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44362. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44363. }
  44364. }
  44365. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44366. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44367. }
  44368. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44369. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44370. }
  44371. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44372. if (this._metallicTexture) {
  44373. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44374. }
  44375. else if (this._reflectivityTexture) {
  44376. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44377. }
  44378. if (this._microSurfaceTexture) {
  44379. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44380. }
  44381. }
  44382. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44383. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44384. }
  44385. }
  44386. // Clip plane
  44387. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44388. // Colors
  44389. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44390. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44391. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44392. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44393. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44394. }
  44395. if (mustRebind || !this.isFrozen) {
  44396. // Lights
  44397. if (scene.lightsEnabled && !this._disableLighting) {
  44398. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44399. }
  44400. // View
  44401. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44402. this.bindView(effect);
  44403. }
  44404. // Fog
  44405. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44406. // Morph targets
  44407. if (defines.NUM_MORPH_INFLUENCERS) {
  44408. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44409. }
  44410. // image processing
  44411. this._imageProcessingConfiguration.bind(this._activeEffect);
  44412. // Log. depth
  44413. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44414. }
  44415. this._uniformBuffer.update();
  44416. this._afterBind(mesh, this._activeEffect);
  44417. };
  44418. /**
  44419. * Returns the animatable textures.
  44420. * @returns - Array of animatable textures.
  44421. */
  44422. PBRBaseMaterial.prototype.getAnimatables = function () {
  44423. var results = [];
  44424. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44425. results.push(this._albedoTexture);
  44426. }
  44427. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44428. results.push(this._ambientTexture);
  44429. }
  44430. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44431. results.push(this._opacityTexture);
  44432. }
  44433. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44434. results.push(this._reflectionTexture);
  44435. }
  44436. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44437. results.push(this._emissiveTexture);
  44438. }
  44439. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44440. results.push(this._metallicTexture);
  44441. }
  44442. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44443. results.push(this._reflectivityTexture);
  44444. }
  44445. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44446. results.push(this._bumpTexture);
  44447. }
  44448. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44449. results.push(this._lightmapTexture);
  44450. }
  44451. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44452. results.push(this._refractionTexture);
  44453. }
  44454. return results;
  44455. };
  44456. /**
  44457. * Returns the texture used for reflections.
  44458. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44459. */
  44460. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44461. if (this._reflectionTexture) {
  44462. return this._reflectionTexture;
  44463. }
  44464. return this.getScene().environmentTexture;
  44465. };
  44466. /**
  44467. * Returns the texture used for refraction or null if none is used.
  44468. * @returns - Refection texture if present. If no refraction texture and refraction
  44469. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44470. */
  44471. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44472. if (this._refractionTexture) {
  44473. return this._refractionTexture;
  44474. }
  44475. if (this._linkRefractionWithTransparency) {
  44476. return this.getScene().environmentTexture;
  44477. }
  44478. return null;
  44479. };
  44480. /**
  44481. * Disposes the resources of the material.
  44482. * @param forceDisposeEffect - Forces the disposal of effects.
  44483. * @param forceDisposeTextures - Forces the disposal of all textures.
  44484. */
  44485. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44486. if (forceDisposeTextures) {
  44487. if (this._albedoTexture) {
  44488. this._albedoTexture.dispose();
  44489. }
  44490. if (this._ambientTexture) {
  44491. this._ambientTexture.dispose();
  44492. }
  44493. if (this._opacityTexture) {
  44494. this._opacityTexture.dispose();
  44495. }
  44496. if (this._reflectionTexture) {
  44497. this._reflectionTexture.dispose();
  44498. }
  44499. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44500. this._environmentBRDFTexture.dispose();
  44501. }
  44502. if (this._emissiveTexture) {
  44503. this._emissiveTexture.dispose();
  44504. }
  44505. if (this._metallicTexture) {
  44506. this._metallicTexture.dispose();
  44507. }
  44508. if (this._reflectivityTexture) {
  44509. this._reflectivityTexture.dispose();
  44510. }
  44511. if (this._bumpTexture) {
  44512. this._bumpTexture.dispose();
  44513. }
  44514. if (this._lightmapTexture) {
  44515. this._lightmapTexture.dispose();
  44516. }
  44517. if (this._refractionTexture) {
  44518. this._refractionTexture.dispose();
  44519. }
  44520. }
  44521. this._renderTargets.dispose();
  44522. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44523. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44524. }
  44525. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44526. };
  44527. /**
  44528. * Stores the reflectivity values based on metallic roughness workflow.
  44529. */
  44530. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44531. __decorate([
  44532. BABYLON.serializeAsImageProcessingConfiguration()
  44533. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44534. __decorate([
  44535. BABYLON.serialize()
  44536. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44537. __decorate([
  44538. BABYLON.serialize()
  44539. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44540. return PBRBaseMaterial;
  44541. }(BABYLON.PushMaterial));
  44542. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44543. })(BABYLON || (BABYLON = {}));
  44544. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44545. var BABYLON;
  44546. (function (BABYLON) {
  44547. /**
  44548. * The Physically based simple base material of BJS.
  44549. *
  44550. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44551. * It is used as the base class for both the specGloss and metalRough conventions.
  44552. */
  44553. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44554. __extends(PBRBaseSimpleMaterial, _super);
  44555. /**
  44556. * Instantiates a new PBRMaterial instance.
  44557. *
  44558. * @param name The material name
  44559. * @param scene The scene the material will be use in.
  44560. */
  44561. function PBRBaseSimpleMaterial(name, scene) {
  44562. var _this = _super.call(this, name, scene) || this;
  44563. /**
  44564. * Number of Simultaneous lights allowed on the material.
  44565. */
  44566. _this.maxSimultaneousLights = 4;
  44567. /**
  44568. * If sets to true, disables all the lights affecting the material.
  44569. */
  44570. _this.disableLighting = false;
  44571. /**
  44572. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44573. */
  44574. _this.invertNormalMapX = false;
  44575. /**
  44576. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44577. */
  44578. _this.invertNormalMapY = false;
  44579. /**
  44580. * Emissivie color used to self-illuminate the model.
  44581. */
  44582. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44583. /**
  44584. * Occlusion Channel Strenght.
  44585. */
  44586. _this.occlusionStrength = 1.0;
  44587. _this.useLightmapAsShadowmap = false;
  44588. _this._useAlphaFromAlbedoTexture = true;
  44589. _this._useAmbientInGrayScale = true;
  44590. return _this;
  44591. }
  44592. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44593. /**
  44594. * Gets the current double sided mode.
  44595. */
  44596. get: function () {
  44597. return this._twoSidedLighting;
  44598. },
  44599. /**
  44600. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44601. */
  44602. set: function (value) {
  44603. if (this._twoSidedLighting === value) {
  44604. return;
  44605. }
  44606. this._twoSidedLighting = value;
  44607. this.backFaceCulling = !value;
  44608. this._markAllSubMeshesAsTexturesDirty();
  44609. },
  44610. enumerable: true,
  44611. configurable: true
  44612. });
  44613. /**
  44614. * Return the active textures of the material.
  44615. */
  44616. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44617. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44618. if (this.environmentTexture) {
  44619. activeTextures.push(this.environmentTexture);
  44620. }
  44621. if (this.normalTexture) {
  44622. activeTextures.push(this.normalTexture);
  44623. }
  44624. if (this.emissiveTexture) {
  44625. activeTextures.push(this.emissiveTexture);
  44626. }
  44627. if (this.occlusionTexture) {
  44628. activeTextures.push(this.occlusionTexture);
  44629. }
  44630. if (this.lightmapTexture) {
  44631. activeTextures.push(this.lightmapTexture);
  44632. }
  44633. return activeTextures;
  44634. };
  44635. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44636. if (_super.prototype.hasTexture.call(this, texture)) {
  44637. return true;
  44638. }
  44639. if (this.lightmapTexture === texture) {
  44640. return true;
  44641. }
  44642. return false;
  44643. };
  44644. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44645. return "PBRBaseSimpleMaterial";
  44646. };
  44647. __decorate([
  44648. BABYLON.serialize(),
  44649. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44650. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44651. __decorate([
  44652. BABYLON.serialize(),
  44653. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44654. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44655. __decorate([
  44656. BABYLON.serializeAsTexture(),
  44657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44658. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44659. __decorate([
  44660. BABYLON.serialize(),
  44661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44662. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44663. __decorate([
  44664. BABYLON.serialize(),
  44665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44666. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44667. __decorate([
  44668. BABYLON.serializeAsTexture(),
  44669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44670. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44671. __decorate([
  44672. BABYLON.serializeAsColor3("emissive"),
  44673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44674. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44675. __decorate([
  44676. BABYLON.serializeAsTexture(),
  44677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44678. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44679. __decorate([
  44680. BABYLON.serialize(),
  44681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44682. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44683. __decorate([
  44684. BABYLON.serializeAsTexture(),
  44685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44686. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44687. __decorate([
  44688. BABYLON.serialize(),
  44689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44690. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44691. __decorate([
  44692. BABYLON.serialize()
  44693. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44694. __decorate([
  44695. BABYLON.serializeAsTexture(),
  44696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44697. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44698. __decorate([
  44699. BABYLON.serialize(),
  44700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44701. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44702. return PBRBaseSimpleMaterial;
  44703. }(BABYLON.PBRBaseMaterial));
  44704. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44705. })(BABYLON || (BABYLON = {}));
  44706. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44707. var BABYLON;
  44708. (function (BABYLON) {
  44709. /**
  44710. * The Physically based material of BJS.
  44711. *
  44712. * This offers the main features of a standard PBR material.
  44713. * For more information, please refer to the documentation :
  44714. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44715. */
  44716. var PBRMaterial = /** @class */ (function (_super) {
  44717. __extends(PBRMaterial, _super);
  44718. /**
  44719. * Instantiates a new PBRMaterial instance.
  44720. *
  44721. * @param name The material name
  44722. * @param scene The scene the material will be use in.
  44723. */
  44724. function PBRMaterial(name, scene) {
  44725. var _this = _super.call(this, name, scene) || this;
  44726. /**
  44727. * Intensity of the direct lights e.g. the four lights available in your scene.
  44728. * This impacts both the direct diffuse and specular highlights.
  44729. */
  44730. _this.directIntensity = 1.0;
  44731. /**
  44732. * Intensity of the emissive part of the material.
  44733. * This helps controlling the emissive effect without modifying the emissive color.
  44734. */
  44735. _this.emissiveIntensity = 1.0;
  44736. /**
  44737. * Intensity of the environment e.g. how much the environment will light the object
  44738. * either through harmonics for rough material or through the refelction for shiny ones.
  44739. */
  44740. _this.environmentIntensity = 1.0;
  44741. /**
  44742. * This is a special control allowing the reduction of the specular highlights coming from the
  44743. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44744. */
  44745. _this.specularIntensity = 1.0;
  44746. /**
  44747. * Debug Control allowing disabling the bump map on this material.
  44748. */
  44749. _this.disableBumpMap = false;
  44750. /**
  44751. * AKA Occlusion Texture Intensity in other nomenclature.
  44752. */
  44753. _this.ambientTextureStrength = 1.0;
  44754. /**
  44755. * The color of a material in ambient lighting.
  44756. */
  44757. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44758. /**
  44759. * AKA Diffuse Color in other nomenclature.
  44760. */
  44761. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44762. /**
  44763. * AKA Specular Color in other nomenclature.
  44764. */
  44765. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44766. /**
  44767. * The color reflected from the material.
  44768. */
  44769. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44770. /**
  44771. * The color emitted from the material.
  44772. */
  44773. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44774. /**
  44775. * AKA Glossiness in other nomenclature.
  44776. */
  44777. _this.microSurface = 1.0;
  44778. /**
  44779. * source material index of refraction (IOR)' / 'destination material IOR.
  44780. */
  44781. _this.indexOfRefraction = 0.66;
  44782. /**
  44783. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44784. */
  44785. _this.invertRefractionY = false;
  44786. /**
  44787. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44788. * Materials half opaque for instance using refraction could benefit from this control.
  44789. */
  44790. _this.linkRefractionWithTransparency = false;
  44791. _this.useLightmapAsShadowmap = false;
  44792. /**
  44793. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44794. */
  44795. _this.useAlphaFromAlbedoTexture = false;
  44796. /**
  44797. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44798. */
  44799. _this.forceAlphaTest = false;
  44800. /**
  44801. * Defines the alpha limits in alpha test mode.
  44802. */
  44803. _this.alphaCutOff = 0.4;
  44804. /**
  44805. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44806. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44807. */
  44808. _this.useSpecularOverAlpha = true;
  44809. /**
  44810. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44811. */
  44812. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44813. /**
  44814. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44815. */
  44816. _this.useRoughnessFromMetallicTextureAlpha = true;
  44817. /**
  44818. * Specifies if the metallic texture contains the roughness information in its green channel.
  44819. */
  44820. _this.useRoughnessFromMetallicTextureGreen = false;
  44821. /**
  44822. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44823. */
  44824. _this.useMetallnessFromMetallicTextureBlue = false;
  44825. /**
  44826. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44827. */
  44828. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44829. /**
  44830. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44831. */
  44832. _this.useAmbientInGrayScale = false;
  44833. /**
  44834. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44835. * The material will try to infer what glossiness each pixel should be.
  44836. */
  44837. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44838. /**
  44839. * BJS is using an harcoded light falloff based on a manually sets up range.
  44840. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44841. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44842. */
  44843. _this.usePhysicalLightFalloff = true;
  44844. /**
  44845. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44846. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44847. */
  44848. _this.useRadianceOverAlpha = true;
  44849. /**
  44850. * Allows using an object space normal map (instead of tangent space).
  44851. */
  44852. _this.useObjectSpaceNormalMap = false;
  44853. /**
  44854. * Allows using the bump map in parallax mode.
  44855. */
  44856. _this.useParallax = false;
  44857. /**
  44858. * Allows using the bump map in parallax occlusion mode.
  44859. */
  44860. _this.useParallaxOcclusion = false;
  44861. /**
  44862. * Controls the scale bias of the parallax mode.
  44863. */
  44864. _this.parallaxScaleBias = 0.05;
  44865. /**
  44866. * If sets to true, disables all the lights affecting the material.
  44867. */
  44868. _this.disableLighting = false;
  44869. /**
  44870. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44871. */
  44872. _this.forceIrradianceInFragment = false;
  44873. /**
  44874. * Number of Simultaneous lights allowed on the material.
  44875. */
  44876. _this.maxSimultaneousLights = 4;
  44877. /**
  44878. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44879. */
  44880. _this.invertNormalMapX = false;
  44881. /**
  44882. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44883. */
  44884. _this.invertNormalMapY = false;
  44885. /**
  44886. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44887. */
  44888. _this.twoSidedLighting = false;
  44889. /**
  44890. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44891. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44892. */
  44893. _this.useAlphaFresnel = false;
  44894. /**
  44895. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44896. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44897. */
  44898. _this.useLinearAlphaFresnel = false;
  44899. /**
  44900. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44901. * And/Or occlude the blended part.
  44902. */
  44903. _this.environmentBRDFTexture = null;
  44904. /**
  44905. * Force normal to face away from face.
  44906. */
  44907. _this.forceNormalForward = false;
  44908. /**
  44909. * Enables specular anti aliasing in the PBR shader.
  44910. * It will both interacts on the Geometry for analytical and IBL lighting.
  44911. * It also prefilter the roughness map based on the bump values.
  44912. */
  44913. _this.enableSpecularAntiAliasing = false;
  44914. /**
  44915. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44916. * makes the reflect vector face the model (under horizon).
  44917. */
  44918. _this.useHorizonOcclusion = true;
  44919. /**
  44920. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44921. * too much the area relying on ambient texture to define their ambient occlusion.
  44922. */
  44923. _this.useRadianceOcclusion = true;
  44924. /**
  44925. * If set to true, no lighting calculations will be applied.
  44926. */
  44927. _this.unlit = false;
  44928. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44929. return _this;
  44930. }
  44931. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  44932. /**
  44933. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  44934. */
  44935. get: function () {
  44936. return this._PBRMATERIAL_OPAQUE;
  44937. },
  44938. enumerable: true,
  44939. configurable: true
  44940. });
  44941. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  44942. /**
  44943. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  44944. */
  44945. get: function () {
  44946. return this._PBRMATERIAL_ALPHATEST;
  44947. },
  44948. enumerable: true,
  44949. configurable: true
  44950. });
  44951. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  44952. /**
  44953. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44954. */
  44955. get: function () {
  44956. return this._PBRMATERIAL_ALPHABLEND;
  44957. },
  44958. enumerable: true,
  44959. configurable: true
  44960. });
  44961. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  44962. /**
  44963. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  44964. * They are also discarded below the alpha cutoff threshold to improve performances.
  44965. */
  44966. get: function () {
  44967. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  44968. },
  44969. enumerable: true,
  44970. configurable: true
  44971. });
  44972. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  44973. /**
  44974. * Gets the image processing configuration used either in this material.
  44975. */
  44976. get: function () {
  44977. return this._imageProcessingConfiguration;
  44978. },
  44979. /**
  44980. * Sets the Default image processing configuration used either in the this material.
  44981. *
  44982. * If sets to null, the scene one is in use.
  44983. */
  44984. set: function (value) {
  44985. this._attachImageProcessingConfiguration(value);
  44986. // Ensure the effect will be rebuilt.
  44987. this._markAllSubMeshesAsTexturesDirty();
  44988. },
  44989. enumerable: true,
  44990. configurable: true
  44991. });
  44992. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  44993. /**
  44994. * Gets wether the color curves effect is enabled.
  44995. */
  44996. get: function () {
  44997. return this.imageProcessingConfiguration.colorCurvesEnabled;
  44998. },
  44999. /**
  45000. * Sets wether the color curves effect is enabled.
  45001. */
  45002. set: function (value) {
  45003. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45004. },
  45005. enumerable: true,
  45006. configurable: true
  45007. });
  45008. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45009. /**
  45010. * Gets wether the color grading effect is enabled.
  45011. */
  45012. get: function () {
  45013. return this.imageProcessingConfiguration.colorGradingEnabled;
  45014. },
  45015. /**
  45016. * Gets wether the color grading effect is enabled.
  45017. */
  45018. set: function (value) {
  45019. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45020. },
  45021. enumerable: true,
  45022. configurable: true
  45023. });
  45024. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45025. /**
  45026. * Gets wether tonemapping is enabled or not.
  45027. */
  45028. get: function () {
  45029. return this._imageProcessingConfiguration.toneMappingEnabled;
  45030. },
  45031. /**
  45032. * Sets wether tonemapping is enabled or not
  45033. */
  45034. set: function (value) {
  45035. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45036. },
  45037. enumerable: true,
  45038. configurable: true
  45039. });
  45040. ;
  45041. ;
  45042. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45043. /**
  45044. * The camera exposure used on this material.
  45045. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45046. * This corresponds to a photographic exposure.
  45047. */
  45048. get: function () {
  45049. return this._imageProcessingConfiguration.exposure;
  45050. },
  45051. /**
  45052. * The camera exposure used on this material.
  45053. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45054. * This corresponds to a photographic exposure.
  45055. */
  45056. set: function (value) {
  45057. this._imageProcessingConfiguration.exposure = value;
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. ;
  45063. ;
  45064. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45065. /**
  45066. * Gets The camera contrast used on this material.
  45067. */
  45068. get: function () {
  45069. return this._imageProcessingConfiguration.contrast;
  45070. },
  45071. /**
  45072. * Sets The camera contrast used on this material.
  45073. */
  45074. set: function (value) {
  45075. this._imageProcessingConfiguration.contrast = value;
  45076. },
  45077. enumerable: true,
  45078. configurable: true
  45079. });
  45080. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45081. /**
  45082. * Gets the Color Grading 2D Lookup Texture.
  45083. */
  45084. get: function () {
  45085. return this._imageProcessingConfiguration.colorGradingTexture;
  45086. },
  45087. /**
  45088. * Sets the Color Grading 2D Lookup Texture.
  45089. */
  45090. set: function (value) {
  45091. this._imageProcessingConfiguration.colorGradingTexture = value;
  45092. },
  45093. enumerable: true,
  45094. configurable: true
  45095. });
  45096. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45097. /**
  45098. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45099. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45100. * 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;
  45101. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45102. */
  45103. get: function () {
  45104. return this._imageProcessingConfiguration.colorCurves;
  45105. },
  45106. /**
  45107. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45108. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45109. * 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;
  45110. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45111. */
  45112. set: function (value) {
  45113. this._imageProcessingConfiguration.colorCurves = value;
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. /**
  45119. * Returns the name of this material class.
  45120. */
  45121. PBRMaterial.prototype.getClassName = function () {
  45122. return "PBRMaterial";
  45123. };
  45124. /**
  45125. * Returns an array of the actively used textures.
  45126. * @returns - Array of BaseTextures
  45127. */
  45128. PBRMaterial.prototype.getActiveTextures = function () {
  45129. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45130. if (this._albedoTexture) {
  45131. activeTextures.push(this._albedoTexture);
  45132. }
  45133. if (this._ambientTexture) {
  45134. activeTextures.push(this._ambientTexture);
  45135. }
  45136. if (this._opacityTexture) {
  45137. activeTextures.push(this._opacityTexture);
  45138. }
  45139. if (this._reflectionTexture) {
  45140. activeTextures.push(this._reflectionTexture);
  45141. }
  45142. if (this._emissiveTexture) {
  45143. activeTextures.push(this._emissiveTexture);
  45144. }
  45145. if (this._reflectivityTexture) {
  45146. activeTextures.push(this._reflectivityTexture);
  45147. }
  45148. if (this._metallicTexture) {
  45149. activeTextures.push(this._metallicTexture);
  45150. }
  45151. if (this._microSurfaceTexture) {
  45152. activeTextures.push(this._microSurfaceTexture);
  45153. }
  45154. if (this._bumpTexture) {
  45155. activeTextures.push(this._bumpTexture);
  45156. }
  45157. if (this._lightmapTexture) {
  45158. activeTextures.push(this._lightmapTexture);
  45159. }
  45160. if (this._refractionTexture) {
  45161. activeTextures.push(this._refractionTexture);
  45162. }
  45163. return activeTextures;
  45164. };
  45165. /**
  45166. * Checks to see if a texture is used in the material.
  45167. * @param texture - Base texture to use.
  45168. * @returns - Boolean specifying if a texture is used in the material.
  45169. */
  45170. PBRMaterial.prototype.hasTexture = function (texture) {
  45171. if (_super.prototype.hasTexture.call(this, texture)) {
  45172. return true;
  45173. }
  45174. if (this._albedoTexture === texture) {
  45175. return true;
  45176. }
  45177. if (this._ambientTexture === texture) {
  45178. return true;
  45179. }
  45180. if (this._opacityTexture === texture) {
  45181. return true;
  45182. }
  45183. if (this._reflectionTexture === texture) {
  45184. return true;
  45185. }
  45186. if (this._reflectivityTexture === texture) {
  45187. return true;
  45188. }
  45189. if (this._metallicTexture === texture) {
  45190. return true;
  45191. }
  45192. if (this._microSurfaceTexture === texture) {
  45193. return true;
  45194. }
  45195. if (this._bumpTexture === texture) {
  45196. return true;
  45197. }
  45198. if (this._lightmapTexture === texture) {
  45199. return true;
  45200. }
  45201. if (this._refractionTexture === texture) {
  45202. return true;
  45203. }
  45204. return false;
  45205. };
  45206. /**
  45207. * Makes a duplicate of the current material.
  45208. * @param name - name to use for the new material.
  45209. */
  45210. PBRMaterial.prototype.clone = function (name) {
  45211. var _this = this;
  45212. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45213. clone.id = name;
  45214. clone.name = name;
  45215. return clone;
  45216. };
  45217. /**
  45218. * Serializes this PBR Material.
  45219. * @returns - An object with the serialized material.
  45220. */
  45221. PBRMaterial.prototype.serialize = function () {
  45222. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45223. serializationObject.customType = "BABYLON.PBRMaterial";
  45224. return serializationObject;
  45225. };
  45226. // Statics
  45227. /**
  45228. * Parses a PBR Material from a serialized object.
  45229. * @param source - Serialized object.
  45230. * @param scene - BJS scene instance.
  45231. * @param rootUrl - url for the scene object
  45232. * @returns - PBRMaterial
  45233. */
  45234. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45235. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45236. };
  45237. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45238. /**
  45239. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45240. */
  45241. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45242. /**
  45243. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45244. */
  45245. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45246. /**
  45247. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45248. * They are also discarded below the alpha cutoff threshold to improve performances.
  45249. */
  45250. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45251. __decorate([
  45252. BABYLON.serialize(),
  45253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45254. ], PBRMaterial.prototype, "directIntensity", void 0);
  45255. __decorate([
  45256. BABYLON.serialize(),
  45257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45258. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45259. __decorate([
  45260. BABYLON.serialize(),
  45261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45262. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45263. __decorate([
  45264. BABYLON.serialize(),
  45265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45266. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45267. __decorate([
  45268. BABYLON.serialize(),
  45269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45270. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45271. __decorate([
  45272. BABYLON.serializeAsTexture(),
  45273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45274. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45275. __decorate([
  45276. BABYLON.serializeAsTexture(),
  45277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45278. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45279. __decorate([
  45280. BABYLON.serialize(),
  45281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45282. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45283. __decorate([
  45284. BABYLON.serializeAsTexture(),
  45285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45286. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45287. __decorate([
  45288. BABYLON.serializeAsTexture(),
  45289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45290. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45291. __decorate([
  45292. BABYLON.serializeAsTexture(),
  45293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45294. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45295. __decorate([
  45296. BABYLON.serializeAsTexture(),
  45297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45298. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45299. __decorate([
  45300. BABYLON.serializeAsTexture(),
  45301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45302. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45303. __decorate([
  45304. BABYLON.serialize(),
  45305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45306. ], PBRMaterial.prototype, "metallic", void 0);
  45307. __decorate([
  45308. BABYLON.serialize(),
  45309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45310. ], PBRMaterial.prototype, "roughness", void 0);
  45311. __decorate([
  45312. BABYLON.serializeAsTexture(),
  45313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45314. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45315. __decorate([
  45316. BABYLON.serializeAsTexture(),
  45317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45318. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45319. __decorate([
  45320. BABYLON.serializeAsTexture(),
  45321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45322. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45323. __decorate([
  45324. BABYLON.serializeAsTexture(),
  45325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45326. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45327. __decorate([
  45328. BABYLON.serializeAsColor3("ambient"),
  45329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45330. ], PBRMaterial.prototype, "ambientColor", void 0);
  45331. __decorate([
  45332. BABYLON.serializeAsColor3("albedo"),
  45333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45334. ], PBRMaterial.prototype, "albedoColor", void 0);
  45335. __decorate([
  45336. BABYLON.serializeAsColor3("reflectivity"),
  45337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45338. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45339. __decorate([
  45340. BABYLON.serializeAsColor3("reflection"),
  45341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45342. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45343. __decorate([
  45344. BABYLON.serializeAsColor3("emissive"),
  45345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45346. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45347. __decorate([
  45348. BABYLON.serialize(),
  45349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45350. ], PBRMaterial.prototype, "microSurface", void 0);
  45351. __decorate([
  45352. BABYLON.serialize(),
  45353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45354. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45355. __decorate([
  45356. BABYLON.serialize(),
  45357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45358. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45359. __decorate([
  45360. BABYLON.serialize(),
  45361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45362. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45363. __decorate([
  45364. BABYLON.serialize(),
  45365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45366. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45367. __decorate([
  45368. BABYLON.serialize(),
  45369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45370. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45371. __decorate([
  45372. BABYLON.serialize(),
  45373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45374. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45375. __decorate([
  45376. BABYLON.serialize(),
  45377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45378. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45379. __decorate([
  45380. BABYLON.serialize(),
  45381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45382. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45383. __decorate([
  45384. BABYLON.serialize(),
  45385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45386. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45387. __decorate([
  45388. BABYLON.serialize(),
  45389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45390. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45411. __decorate([
  45412. BABYLON.serialize(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45415. __decorate([
  45416. BABYLON.serialize(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45423. __decorate([
  45424. BABYLON.serialize(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45426. ], PBRMaterial.prototype, "useParallax", void 0);
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45438. ], PBRMaterial.prototype, "disableLighting", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45446. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45447. __decorate([
  45448. BABYLON.serialize(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45451. __decorate([
  45452. BABYLON.serialize(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45459. __decorate([
  45460. BABYLON.serialize(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45462. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45463. __decorate([
  45464. BABYLON.serialize(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsTexture(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45471. __decorate([
  45472. BABYLON.serialize(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45475. __decorate([
  45476. BABYLON.serialize(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45490. ], PBRMaterial.prototype, "unlit", void 0);
  45491. return PBRMaterial;
  45492. }(BABYLON.PBRBaseMaterial));
  45493. BABYLON.PBRMaterial = PBRMaterial;
  45494. })(BABYLON || (BABYLON = {}));
  45495. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45496. var BABYLON;
  45497. (function (BABYLON) {
  45498. /**
  45499. * The PBR material of BJS following the metal roughness convention.
  45500. *
  45501. * This fits to the PBR convention in the GLTF definition:
  45502. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45503. */
  45504. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45505. __extends(PBRMetallicRoughnessMaterial, _super);
  45506. /**
  45507. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45508. *
  45509. * @param name The material name
  45510. * @param scene The scene the material will be use in.
  45511. */
  45512. function PBRMetallicRoughnessMaterial(name, scene) {
  45513. var _this = _super.call(this, name, scene) || this;
  45514. _this._useRoughnessFromMetallicTextureAlpha = false;
  45515. _this._useRoughnessFromMetallicTextureGreen = true;
  45516. _this._useMetallnessFromMetallicTextureBlue = true;
  45517. _this.metallic = 1.0;
  45518. _this.roughness = 1.0;
  45519. return _this;
  45520. }
  45521. /**
  45522. * Return the currrent class name of the material.
  45523. */
  45524. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45525. return "PBRMetallicRoughnessMaterial";
  45526. };
  45527. /**
  45528. * Return the active textures of the material.
  45529. */
  45530. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45531. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45532. if (this.baseTexture) {
  45533. activeTextures.push(this.baseTexture);
  45534. }
  45535. if (this.metallicRoughnessTexture) {
  45536. activeTextures.push(this.metallicRoughnessTexture);
  45537. }
  45538. return activeTextures;
  45539. };
  45540. /**
  45541. * Checks to see if a texture is used in the material.
  45542. * @param texture - Base texture to use.
  45543. * @returns - Boolean specifying if a texture is used in the material.
  45544. */
  45545. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45546. if (_super.prototype.hasTexture.call(this, texture)) {
  45547. return true;
  45548. }
  45549. if (this.baseTexture === texture) {
  45550. return true;
  45551. }
  45552. if (this.metallicRoughnessTexture === texture) {
  45553. return true;
  45554. }
  45555. return false;
  45556. };
  45557. /**
  45558. * Makes a duplicate of the current material.
  45559. * @param name - name to use for the new material.
  45560. */
  45561. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45562. var _this = this;
  45563. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45564. clone.id = name;
  45565. clone.name = name;
  45566. return clone;
  45567. };
  45568. /**
  45569. * Serialize the material to a parsable JSON object.
  45570. */
  45571. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45572. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45573. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45574. return serializationObject;
  45575. };
  45576. /**
  45577. * Parses a JSON object correponding to the serialize function.
  45578. */
  45579. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45580. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45581. };
  45582. __decorate([
  45583. BABYLON.serializeAsColor3(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45585. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45586. __decorate([
  45587. BABYLON.serializeAsTexture(),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45589. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45590. __decorate([
  45591. BABYLON.serialize(),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45594. __decorate([
  45595. BABYLON.serialize(),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45598. __decorate([
  45599. BABYLON.serializeAsTexture(),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45601. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45602. return PBRMetallicRoughnessMaterial;
  45603. }(BABYLON.PBRBaseSimpleMaterial));
  45604. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45605. })(BABYLON || (BABYLON = {}));
  45606. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45607. var BABYLON;
  45608. (function (BABYLON) {
  45609. /**
  45610. * The PBR material of BJS following the specular glossiness convention.
  45611. *
  45612. * This fits to the PBR convention in the GLTF definition:
  45613. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45614. */
  45615. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45616. __extends(PBRSpecularGlossinessMaterial, _super);
  45617. /**
  45618. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45619. *
  45620. * @param name The material name
  45621. * @param scene The scene the material will be use in.
  45622. */
  45623. function PBRSpecularGlossinessMaterial(name, scene) {
  45624. var _this = _super.call(this, name, scene) || this;
  45625. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45626. return _this;
  45627. }
  45628. /**
  45629. * Return the currrent class name of the material.
  45630. */
  45631. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45632. return "PBRSpecularGlossinessMaterial";
  45633. };
  45634. /**
  45635. * Return the active textures of the material.
  45636. */
  45637. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45638. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45639. if (this.diffuseTexture) {
  45640. activeTextures.push(this.diffuseTexture);
  45641. }
  45642. if (this.specularGlossinessTexture) {
  45643. activeTextures.push(this.specularGlossinessTexture);
  45644. }
  45645. return activeTextures;
  45646. };
  45647. /**
  45648. * Checks to see if a texture is used in the material.
  45649. * @param texture - Base texture to use.
  45650. * @returns - Boolean specifying if a texture is used in the material.
  45651. */
  45652. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45653. if (_super.prototype.hasTexture.call(this, texture)) {
  45654. return true;
  45655. }
  45656. if (this.diffuseTexture === texture) {
  45657. return true;
  45658. }
  45659. if (this.specularGlossinessTexture === texture) {
  45660. return true;
  45661. }
  45662. return false;
  45663. };
  45664. /**
  45665. * Makes a duplicate of the current material.
  45666. * @param name - name to use for the new material.
  45667. */
  45668. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45669. var _this = this;
  45670. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45671. clone.id = name;
  45672. clone.name = name;
  45673. return clone;
  45674. };
  45675. /**
  45676. * Serialize the material to a parsable JSON object.
  45677. */
  45678. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45679. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45680. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45681. return serializationObject;
  45682. };
  45683. /**
  45684. * Parses a JSON object correponding to the serialize function.
  45685. */
  45686. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45687. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45688. };
  45689. __decorate([
  45690. BABYLON.serializeAsColor3("diffuse"),
  45691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45692. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45693. __decorate([
  45694. BABYLON.serializeAsTexture(),
  45695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45696. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45697. __decorate([
  45698. BABYLON.serializeAsColor3("specular"),
  45699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45700. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45701. __decorate([
  45702. BABYLON.serialize(),
  45703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45704. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45705. __decorate([
  45706. BABYLON.serializeAsTexture(),
  45707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45708. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45709. return PBRSpecularGlossinessMaterial;
  45710. }(BABYLON.PBRBaseSimpleMaterial));
  45711. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45712. })(BABYLON || (BABYLON = {}));
  45713. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45714. var BABYLON;
  45715. (function (BABYLON) {
  45716. BABYLON.CameraInputTypes = {};
  45717. var CameraInputsManager = /** @class */ (function () {
  45718. function CameraInputsManager(camera) {
  45719. this.attached = {};
  45720. this.camera = camera;
  45721. this.checkInputs = function () { };
  45722. }
  45723. /**
  45724. * Add an input method to a camera
  45725. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  45726. * @param input camera input method
  45727. */
  45728. CameraInputsManager.prototype.add = function (input) {
  45729. var type = input.getSimpleName();
  45730. if (this.attached[type]) {
  45731. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45732. return;
  45733. }
  45734. this.attached[type] = input;
  45735. input.camera = this.camera;
  45736. //for checkInputs, we are dynamically creating a function
  45737. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45738. if (input.checkInputs) {
  45739. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45740. }
  45741. if (this.attachedElement) {
  45742. input.attachControl(this.attachedElement);
  45743. }
  45744. };
  45745. /**
  45746. * Remove a specific input method from a camera
  45747. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45748. * @param inputToRemove camera input method
  45749. */
  45750. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45751. for (var cam in this.attached) {
  45752. var input = this.attached[cam];
  45753. if (input === inputToRemove) {
  45754. input.detachControl(this.attachedElement);
  45755. input.camera = null;
  45756. delete this.attached[cam];
  45757. this.rebuildInputCheck();
  45758. }
  45759. }
  45760. };
  45761. CameraInputsManager.prototype.removeByType = function (inputType) {
  45762. for (var cam in this.attached) {
  45763. var input = this.attached[cam];
  45764. if (input.getClassName() === inputType) {
  45765. input.detachControl(this.attachedElement);
  45766. input.camera = null;
  45767. delete this.attached[cam];
  45768. this.rebuildInputCheck();
  45769. }
  45770. }
  45771. };
  45772. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45773. var current = this.checkInputs;
  45774. return function () {
  45775. current();
  45776. fn();
  45777. };
  45778. };
  45779. CameraInputsManager.prototype.attachInput = function (input) {
  45780. if (this.attachedElement) {
  45781. input.attachControl(this.attachedElement, this.noPreventDefault);
  45782. }
  45783. };
  45784. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45785. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45786. if (this.attachedElement) {
  45787. return;
  45788. }
  45789. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45790. this.attachedElement = element;
  45791. this.noPreventDefault = noPreventDefault;
  45792. for (var cam in this.attached) {
  45793. this.attached[cam].attachControl(element, noPreventDefault);
  45794. }
  45795. };
  45796. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45797. if (disconnect === void 0) { disconnect = false; }
  45798. if (this.attachedElement !== element) {
  45799. return;
  45800. }
  45801. for (var cam in this.attached) {
  45802. this.attached[cam].detachControl(element);
  45803. if (disconnect) {
  45804. this.attached[cam].camera = null;
  45805. }
  45806. }
  45807. this.attachedElement = null;
  45808. };
  45809. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45810. this.checkInputs = function () { };
  45811. for (var cam in this.attached) {
  45812. var input = this.attached[cam];
  45813. if (input.checkInputs) {
  45814. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45815. }
  45816. }
  45817. };
  45818. /**
  45819. * Remove all attached input methods from a camera
  45820. */
  45821. CameraInputsManager.prototype.clear = function () {
  45822. if (this.attachedElement) {
  45823. this.detachElement(this.attachedElement, true);
  45824. }
  45825. this.attached = {};
  45826. this.attachedElement = null;
  45827. this.checkInputs = function () { };
  45828. };
  45829. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45830. var inputs = {};
  45831. for (var cam in this.attached) {
  45832. var input = this.attached[cam];
  45833. var res = BABYLON.SerializationHelper.Serialize(input);
  45834. inputs[input.getClassName()] = res;
  45835. }
  45836. serializedCamera.inputsmgr = inputs;
  45837. };
  45838. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45839. var parsedInputs = parsedCamera.inputsmgr;
  45840. if (parsedInputs) {
  45841. this.clear();
  45842. for (var n in parsedInputs) {
  45843. var construct = BABYLON.CameraInputTypes[n];
  45844. if (construct) {
  45845. var parsedinput = parsedInputs[n];
  45846. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45847. this.add(input);
  45848. }
  45849. }
  45850. }
  45851. else {
  45852. //2016-03-08 this part is for managing backward compatibility
  45853. for (var n in this.attached) {
  45854. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45855. if (construct) {
  45856. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45857. this.remove(this.attached[n]);
  45858. this.add(input);
  45859. }
  45860. }
  45861. }
  45862. };
  45863. return CameraInputsManager;
  45864. }());
  45865. BABYLON.CameraInputsManager = CameraInputsManager;
  45866. })(BABYLON || (BABYLON = {}));
  45867. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  45868. var BABYLON;
  45869. (function (BABYLON) {
  45870. var TargetCamera = /** @class */ (function (_super) {
  45871. __extends(TargetCamera, _super);
  45872. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  45873. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  45874. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  45875. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45876. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  45877. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  45878. _this.speed = 2.0;
  45879. _this.noRotationConstraint = false;
  45880. _this.lockedTarget = null;
  45881. _this._currentTarget = BABYLON.Vector3.Zero();
  45882. _this._viewMatrix = BABYLON.Matrix.Zero();
  45883. _this._camMatrix = BABYLON.Matrix.Zero();
  45884. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  45885. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  45886. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  45887. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  45888. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  45889. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  45890. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  45891. return _this;
  45892. }
  45893. TargetCamera.prototype.getFrontPosition = function (distance) {
  45894. this.getWorldMatrix();
  45895. var direction = this.getTarget().subtract(this.position);
  45896. direction.normalize();
  45897. direction.scaleInPlace(distance);
  45898. return this.globalPosition.add(direction);
  45899. };
  45900. TargetCamera.prototype._getLockedTargetPosition = function () {
  45901. if (!this.lockedTarget) {
  45902. return null;
  45903. }
  45904. if (this.lockedTarget.absolutePosition) {
  45905. this.lockedTarget.computeWorldMatrix();
  45906. }
  45907. return this.lockedTarget.absolutePosition || this.lockedTarget;
  45908. };
  45909. TargetCamera.prototype.storeState = function () {
  45910. this._storedPosition = this.position.clone();
  45911. this._storedRotation = this.rotation.clone();
  45912. if (this.rotationQuaternion) {
  45913. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  45914. }
  45915. return _super.prototype.storeState.call(this);
  45916. };
  45917. /**
  45918. * Restored camera state. You must call storeState() first
  45919. */
  45920. TargetCamera.prototype._restoreStateValues = function () {
  45921. if (!_super.prototype._restoreStateValues.call(this)) {
  45922. return false;
  45923. }
  45924. this.position = this._storedPosition.clone();
  45925. this.rotation = this._storedRotation.clone();
  45926. if (this.rotationQuaternion) {
  45927. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  45928. }
  45929. this.cameraDirection.copyFromFloats(0, 0, 0);
  45930. this.cameraRotation.copyFromFloats(0, 0);
  45931. return true;
  45932. };
  45933. // Cache
  45934. TargetCamera.prototype._initCache = function () {
  45935. _super.prototype._initCache.call(this);
  45936. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45937. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45938. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45939. };
  45940. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  45941. if (!ignoreParentClass) {
  45942. _super.prototype._updateCache.call(this);
  45943. }
  45944. var lockedTargetPosition = this._getLockedTargetPosition();
  45945. if (!lockedTargetPosition) {
  45946. this._cache.lockedTarget = null;
  45947. }
  45948. else {
  45949. if (!this._cache.lockedTarget) {
  45950. this._cache.lockedTarget = lockedTargetPosition.clone();
  45951. }
  45952. else {
  45953. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  45954. }
  45955. }
  45956. this._cache.rotation.copyFrom(this.rotation);
  45957. if (this.rotationQuaternion)
  45958. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  45959. };
  45960. // Synchronized
  45961. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  45962. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  45963. return false;
  45964. }
  45965. var lockedTargetPosition = this._getLockedTargetPosition();
  45966. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  45967. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  45968. };
  45969. // Methods
  45970. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  45971. var engine = this.getEngine();
  45972. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  45973. };
  45974. // Target
  45975. TargetCamera.prototype.setTarget = function (target) {
  45976. this.upVector.normalize();
  45977. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  45978. this._camMatrix.invert();
  45979. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  45980. var vDir = target.subtract(this.position);
  45981. if (vDir.x >= 0.0) {
  45982. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  45983. }
  45984. else {
  45985. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  45986. }
  45987. this.rotation.z = 0;
  45988. if (isNaN(this.rotation.x)) {
  45989. this.rotation.x = 0;
  45990. }
  45991. if (isNaN(this.rotation.y)) {
  45992. this.rotation.y = 0;
  45993. }
  45994. if (isNaN(this.rotation.z)) {
  45995. this.rotation.z = 0;
  45996. }
  45997. if (this.rotationQuaternion) {
  45998. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  45999. }
  46000. };
  46001. /**
  46002. * Return the current target position of the camera. This value is expressed in local space.
  46003. */
  46004. TargetCamera.prototype.getTarget = function () {
  46005. return this._currentTarget;
  46006. };
  46007. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46008. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46009. };
  46010. TargetCamera.prototype._updatePosition = function () {
  46011. if (this.parent) {
  46012. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46013. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46014. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46015. return;
  46016. }
  46017. this.position.addInPlace(this.cameraDirection);
  46018. };
  46019. TargetCamera.prototype._checkInputs = function () {
  46020. var needToMove = this._decideIfNeedsToMove();
  46021. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46022. // Move
  46023. if (needToMove) {
  46024. this._updatePosition();
  46025. }
  46026. // Rotate
  46027. if (needToRotate) {
  46028. this.rotation.x += this.cameraRotation.x;
  46029. this.rotation.y += this.cameraRotation.y;
  46030. //rotate, if quaternion is set and rotation was used
  46031. if (this.rotationQuaternion) {
  46032. var len = this.rotation.lengthSquared();
  46033. if (len) {
  46034. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46035. }
  46036. }
  46037. if (!this.noRotationConstraint) {
  46038. var limit = (Math.PI / 2) * 0.95;
  46039. if (this.rotation.x > limit)
  46040. this.rotation.x = limit;
  46041. if (this.rotation.x < -limit)
  46042. this.rotation.x = -limit;
  46043. }
  46044. }
  46045. // Inertia
  46046. if (needToMove) {
  46047. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46048. this.cameraDirection.x = 0;
  46049. }
  46050. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46051. this.cameraDirection.y = 0;
  46052. }
  46053. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46054. this.cameraDirection.z = 0;
  46055. }
  46056. this.cameraDirection.scaleInPlace(this.inertia);
  46057. }
  46058. if (needToRotate) {
  46059. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46060. this.cameraRotation.x = 0;
  46061. }
  46062. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46063. this.cameraRotation.y = 0;
  46064. }
  46065. this.cameraRotation.scaleInPlace(this.inertia);
  46066. }
  46067. _super.prototype._checkInputs.call(this);
  46068. };
  46069. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46070. if (this.rotationQuaternion) {
  46071. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46072. }
  46073. else {
  46074. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46075. }
  46076. //update the up vector!
  46077. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46078. };
  46079. TargetCamera.prototype._getViewMatrix = function () {
  46080. if (this.lockedTarget) {
  46081. this.setTarget(this._getLockedTargetPosition());
  46082. }
  46083. // Compute
  46084. this._updateCameraRotationMatrix();
  46085. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46086. // Computing target and final matrix
  46087. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46088. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46089. return this._viewMatrix;
  46090. };
  46091. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46092. if (this.parent) {
  46093. var parentWorldMatrix = this.parent.getWorldMatrix();
  46094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46095. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46096. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46097. this._markSyncedWithParent();
  46098. }
  46099. else {
  46100. this._globalPosition.copyFrom(this.position);
  46101. this._globalCurrentTarget.copyFrom(target);
  46102. this._globalCurrentUpVector.copyFrom(up);
  46103. }
  46104. if (this.getScene().useRightHandedSystem) {
  46105. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46106. }
  46107. else {
  46108. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46109. }
  46110. };
  46111. /**
  46112. * @override
  46113. * Override Camera.createRigCamera
  46114. */
  46115. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46116. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46117. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46118. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46119. if (!this.rotationQuaternion) {
  46120. this.rotationQuaternion = new BABYLON.Quaternion();
  46121. }
  46122. rigCamera._cameraRigParams = {};
  46123. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46124. }
  46125. return rigCamera;
  46126. }
  46127. return null;
  46128. };
  46129. /**
  46130. * @override
  46131. * Override Camera._updateRigCameras
  46132. */
  46133. TargetCamera.prototype._updateRigCameras = function () {
  46134. var camLeft = this._rigCameras[0];
  46135. var camRight = this._rigCameras[1];
  46136. switch (this.cameraRigMode) {
  46137. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46138. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46139. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46140. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46141. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46142. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46143. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46144. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46145. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46146. camLeft.setTarget(this.getTarget());
  46147. camRight.setTarget(this.getTarget());
  46148. break;
  46149. case BABYLON.Camera.RIG_MODE_VR:
  46150. if (camLeft.rotationQuaternion) {
  46151. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46152. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46153. }
  46154. else {
  46155. camLeft.rotation.copyFrom(this.rotation);
  46156. camRight.rotation.copyFrom(this.rotation);
  46157. }
  46158. camLeft.position.copyFrom(this.position);
  46159. camRight.position.copyFrom(this.position);
  46160. break;
  46161. }
  46162. _super.prototype._updateRigCameras.call(this);
  46163. };
  46164. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46165. if (!this._rigCamTransformMatrix) {
  46166. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46167. }
  46168. var target = this.getTarget();
  46169. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46170. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46171. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46172. };
  46173. TargetCamera.prototype.getClassName = function () {
  46174. return "TargetCamera";
  46175. };
  46176. __decorate([
  46177. BABYLON.serializeAsVector3()
  46178. ], TargetCamera.prototype, "rotation", void 0);
  46179. __decorate([
  46180. BABYLON.serialize()
  46181. ], TargetCamera.prototype, "speed", void 0);
  46182. __decorate([
  46183. BABYLON.serializeAsMeshReference("lockedTargetId")
  46184. ], TargetCamera.prototype, "lockedTarget", void 0);
  46185. return TargetCamera;
  46186. }(BABYLON.Camera));
  46187. BABYLON.TargetCamera = TargetCamera;
  46188. })(BABYLON || (BABYLON = {}));
  46189. //# sourceMappingURL=babylon.targetCamera.js.map
  46190. var BABYLON;
  46191. (function (BABYLON) {
  46192. var FreeCameraMouseInput = /** @class */ (function () {
  46193. function FreeCameraMouseInput(touchEnabled) {
  46194. if (touchEnabled === void 0) { touchEnabled = true; }
  46195. this.touchEnabled = touchEnabled;
  46196. this.buttons = [0, 1, 2];
  46197. this.angularSensibility = 2000.0;
  46198. this.previousPosition = null;
  46199. }
  46200. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46201. var _this = this;
  46202. var engine = this.camera.getEngine();
  46203. if (!this._pointerInput) {
  46204. this._pointerInput = function (p, s) {
  46205. var evt = p.event;
  46206. if (engine.isInVRExclusivePointerMode) {
  46207. return;
  46208. }
  46209. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46210. return;
  46211. }
  46212. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46213. return;
  46214. }
  46215. var srcElement = (evt.srcElement || evt.target);
  46216. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46217. try {
  46218. srcElement.setPointerCapture(evt.pointerId);
  46219. }
  46220. catch (e) {
  46221. //Nothing to do with the error. Execution will continue.
  46222. }
  46223. _this.previousPosition = {
  46224. x: evt.clientX,
  46225. y: evt.clientY
  46226. };
  46227. if (!noPreventDefault) {
  46228. evt.preventDefault();
  46229. element.focus();
  46230. }
  46231. }
  46232. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46233. try {
  46234. srcElement.releasePointerCapture(evt.pointerId);
  46235. }
  46236. catch (e) {
  46237. //Nothing to do with the error.
  46238. }
  46239. _this.previousPosition = null;
  46240. if (!noPreventDefault) {
  46241. evt.preventDefault();
  46242. }
  46243. }
  46244. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46245. if (!_this.previousPosition || engine.isPointerLock) {
  46246. return;
  46247. }
  46248. var offsetX = evt.clientX - _this.previousPosition.x;
  46249. if (_this.camera.getScene().useRightHandedSystem)
  46250. offsetX *= -1;
  46251. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46252. offsetX *= -1;
  46253. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46254. var offsetY = evt.clientY - _this.previousPosition.y;
  46255. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46256. _this.previousPosition = {
  46257. x: evt.clientX,
  46258. y: evt.clientY
  46259. };
  46260. if (!noPreventDefault) {
  46261. evt.preventDefault();
  46262. }
  46263. }
  46264. };
  46265. }
  46266. this._onMouseMove = function (evt) {
  46267. if (!engine.isPointerLock) {
  46268. return;
  46269. }
  46270. if (engine.isInVRExclusivePointerMode) {
  46271. return;
  46272. }
  46273. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46274. if (_this.camera.getScene().useRightHandedSystem)
  46275. offsetX *= -1;
  46276. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46277. offsetX *= -1;
  46278. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46279. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46280. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46281. _this.previousPosition = null;
  46282. if (!noPreventDefault) {
  46283. evt.preventDefault();
  46284. }
  46285. };
  46286. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46287. element.addEventListener("mousemove", this._onMouseMove, false);
  46288. };
  46289. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46290. if (this._observer && element) {
  46291. this.camera.getScene().onPointerObservable.remove(this._observer);
  46292. if (this._onMouseMove) {
  46293. element.removeEventListener("mousemove", this._onMouseMove);
  46294. }
  46295. this._observer = null;
  46296. this._onMouseMove = null;
  46297. this.previousPosition = null;
  46298. }
  46299. };
  46300. FreeCameraMouseInput.prototype.getClassName = function () {
  46301. return "FreeCameraMouseInput";
  46302. };
  46303. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46304. return "mouse";
  46305. };
  46306. __decorate([
  46307. BABYLON.serialize()
  46308. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46309. __decorate([
  46310. BABYLON.serialize()
  46311. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46312. return FreeCameraMouseInput;
  46313. }());
  46314. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46315. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46316. })(BABYLON || (BABYLON = {}));
  46317. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46318. var BABYLON;
  46319. (function (BABYLON) {
  46320. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46321. function FreeCameraKeyboardMoveInput() {
  46322. this._keys = new Array();
  46323. this.keysUp = [38];
  46324. this.keysDown = [40];
  46325. this.keysLeft = [37];
  46326. this.keysRight = [39];
  46327. }
  46328. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46329. var _this = this;
  46330. if (this._onCanvasBlurObserver) {
  46331. return;
  46332. }
  46333. this._scene = this.camera.getScene();
  46334. this._engine = this._scene.getEngine();
  46335. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46336. _this._keys = [];
  46337. });
  46338. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46339. var evt = info.event;
  46340. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46341. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46342. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46343. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46344. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46345. var index = _this._keys.indexOf(evt.keyCode);
  46346. if (index === -1) {
  46347. _this._keys.push(evt.keyCode);
  46348. }
  46349. if (!noPreventDefault) {
  46350. evt.preventDefault();
  46351. }
  46352. }
  46353. }
  46354. else {
  46355. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46356. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46357. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46358. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46359. var index = _this._keys.indexOf(evt.keyCode);
  46360. if (index >= 0) {
  46361. _this._keys.splice(index, 1);
  46362. }
  46363. if (!noPreventDefault) {
  46364. evt.preventDefault();
  46365. }
  46366. }
  46367. }
  46368. });
  46369. };
  46370. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46371. if (this._scene) {
  46372. if (this._onKeyboardObserver) {
  46373. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46374. }
  46375. if (this._onCanvasBlurObserver) {
  46376. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46377. }
  46378. this._onKeyboardObserver = null;
  46379. this._onCanvasBlurObserver = null;
  46380. }
  46381. this._keys = [];
  46382. };
  46383. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46384. if (this._onKeyboardObserver) {
  46385. var camera = this.camera;
  46386. // Keyboard
  46387. for (var index = 0; index < this._keys.length; index++) {
  46388. var keyCode = this._keys[index];
  46389. var speed = camera._computeLocalCameraSpeed();
  46390. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46391. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46392. }
  46393. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46394. camera._localDirection.copyFromFloats(0, 0, speed);
  46395. }
  46396. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46397. camera._localDirection.copyFromFloats(speed, 0, 0);
  46398. }
  46399. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46400. camera._localDirection.copyFromFloats(0, 0, -speed);
  46401. }
  46402. if (camera.getScene().useRightHandedSystem) {
  46403. camera._localDirection.z *= -1;
  46404. }
  46405. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46406. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46407. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46408. }
  46409. }
  46410. };
  46411. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46412. return "FreeCameraKeyboardMoveInput";
  46413. };
  46414. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46415. this._keys = [];
  46416. };
  46417. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46418. return "keyboard";
  46419. };
  46420. __decorate([
  46421. BABYLON.serialize()
  46422. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46423. __decorate([
  46424. BABYLON.serialize()
  46425. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46426. __decorate([
  46427. BABYLON.serialize()
  46428. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46429. __decorate([
  46430. BABYLON.serialize()
  46431. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46432. return FreeCameraKeyboardMoveInput;
  46433. }());
  46434. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46435. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46436. })(BABYLON || (BABYLON = {}));
  46437. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46438. var BABYLON;
  46439. (function (BABYLON) {
  46440. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46441. __extends(FreeCameraInputsManager, _super);
  46442. function FreeCameraInputsManager(camera) {
  46443. return _super.call(this, camera) || this;
  46444. }
  46445. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46446. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46447. return this;
  46448. };
  46449. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46450. if (touchEnabled === void 0) { touchEnabled = true; }
  46451. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46452. return this;
  46453. };
  46454. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46455. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46456. return this;
  46457. };
  46458. FreeCameraInputsManager.prototype.addTouch = function () {
  46459. this.add(new BABYLON.FreeCameraTouchInput());
  46460. return this;
  46461. };
  46462. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46463. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46464. return this;
  46465. };
  46466. return FreeCameraInputsManager;
  46467. }(BABYLON.CameraInputsManager));
  46468. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46469. })(BABYLON || (BABYLON = {}));
  46470. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46471. var BABYLON;
  46472. (function (BABYLON) {
  46473. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46474. // Forcing to use the Universal camera
  46475. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46476. });
  46477. var FreeCamera = /** @class */ (function (_super) {
  46478. __extends(FreeCamera, _super);
  46479. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46480. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46481. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46482. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46483. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46484. _this.checkCollisions = false;
  46485. _this.applyGravity = false;
  46486. _this._needMoveForGravity = false;
  46487. _this._oldPosition = BABYLON.Vector3.Zero();
  46488. _this._diffPosition = BABYLON.Vector3.Zero();
  46489. _this._newPosition = BABYLON.Vector3.Zero();
  46490. // Collisions
  46491. _this._collisionMask = -1;
  46492. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46493. if (collidedMesh === void 0) { collidedMesh = null; }
  46494. //TODO move this to the collision coordinator!
  46495. if (_this.getScene().workerCollisions)
  46496. newPosition.multiplyInPlace(_this._collider._radius);
  46497. var updatePosition = function (newPos) {
  46498. _this._newPosition.copyFrom(newPos);
  46499. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46500. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46501. _this.position.addInPlace(_this._diffPosition);
  46502. if (_this.onCollide && collidedMesh) {
  46503. _this.onCollide(collidedMesh);
  46504. }
  46505. }
  46506. };
  46507. updatePosition(newPosition);
  46508. };
  46509. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46510. _this.inputs.addKeyboard().addMouse();
  46511. return _this;
  46512. }
  46513. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46514. //-- begin properties for backward compatibility for inputs
  46515. /**
  46516. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46517. * Higher values reduce sensitivity.
  46518. */
  46519. get: function () {
  46520. var mouse = this.inputs.attached["mouse"];
  46521. if (mouse)
  46522. return mouse.angularSensibility;
  46523. return 0;
  46524. },
  46525. /**
  46526. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46527. * Higher values reduce sensitivity.
  46528. */
  46529. set: function (value) {
  46530. var mouse = this.inputs.attached["mouse"];
  46531. if (mouse)
  46532. mouse.angularSensibility = value;
  46533. },
  46534. enumerable: true,
  46535. configurable: true
  46536. });
  46537. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46538. get: function () {
  46539. var keyboard = this.inputs.attached["keyboard"];
  46540. if (keyboard)
  46541. return keyboard.keysUp;
  46542. return [];
  46543. },
  46544. set: function (value) {
  46545. var keyboard = this.inputs.attached["keyboard"];
  46546. if (keyboard)
  46547. keyboard.keysUp = value;
  46548. },
  46549. enumerable: true,
  46550. configurable: true
  46551. });
  46552. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46553. get: function () {
  46554. var keyboard = this.inputs.attached["keyboard"];
  46555. if (keyboard)
  46556. return keyboard.keysDown;
  46557. return [];
  46558. },
  46559. set: function (value) {
  46560. var keyboard = this.inputs.attached["keyboard"];
  46561. if (keyboard)
  46562. keyboard.keysDown = value;
  46563. },
  46564. enumerable: true,
  46565. configurable: true
  46566. });
  46567. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46568. get: function () {
  46569. var keyboard = this.inputs.attached["keyboard"];
  46570. if (keyboard)
  46571. return keyboard.keysLeft;
  46572. return [];
  46573. },
  46574. set: function (value) {
  46575. var keyboard = this.inputs.attached["keyboard"];
  46576. if (keyboard)
  46577. keyboard.keysLeft = value;
  46578. },
  46579. enumerable: true,
  46580. configurable: true
  46581. });
  46582. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46583. get: function () {
  46584. var keyboard = this.inputs.attached["keyboard"];
  46585. if (keyboard)
  46586. return keyboard.keysRight;
  46587. return [];
  46588. },
  46589. set: function (value) {
  46590. var keyboard = this.inputs.attached["keyboard"];
  46591. if (keyboard)
  46592. keyboard.keysRight = value;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. // Controls
  46598. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46599. this.inputs.attachElement(element, noPreventDefault);
  46600. };
  46601. FreeCamera.prototype.detachControl = function (element) {
  46602. this.inputs.detachElement(element);
  46603. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46604. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46605. };
  46606. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46607. get: function () {
  46608. return this._collisionMask;
  46609. },
  46610. set: function (mask) {
  46611. this._collisionMask = !isNaN(mask) ? mask : -1;
  46612. },
  46613. enumerable: true,
  46614. configurable: true
  46615. });
  46616. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46617. var globalPosition;
  46618. if (this.parent) {
  46619. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46620. }
  46621. else {
  46622. globalPosition = this.position;
  46623. }
  46624. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46625. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46626. if (!this._collider) {
  46627. this._collider = new BABYLON.Collider();
  46628. }
  46629. this._collider._radius = this.ellipsoid;
  46630. this._collider.collisionMask = this._collisionMask;
  46631. //no need for clone, as long as gravity is not on.
  46632. var actualDisplacement = displacement;
  46633. //add gravity to the direction to prevent the dual-collision checking
  46634. if (this.applyGravity) {
  46635. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46636. actualDisplacement = displacement.add(this.getScene().gravity);
  46637. }
  46638. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46639. };
  46640. FreeCamera.prototype._checkInputs = function () {
  46641. if (!this._localDirection) {
  46642. this._localDirection = BABYLON.Vector3.Zero();
  46643. this._transformedDirection = BABYLON.Vector3.Zero();
  46644. }
  46645. this.inputs.checkInputs();
  46646. _super.prototype._checkInputs.call(this);
  46647. };
  46648. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46649. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46650. };
  46651. FreeCamera.prototype._updatePosition = function () {
  46652. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46653. this._collideWithWorld(this.cameraDirection);
  46654. }
  46655. else {
  46656. _super.prototype._updatePosition.call(this);
  46657. }
  46658. };
  46659. FreeCamera.prototype.dispose = function () {
  46660. this.inputs.clear();
  46661. _super.prototype.dispose.call(this);
  46662. };
  46663. FreeCamera.prototype.getClassName = function () {
  46664. return "FreeCamera";
  46665. };
  46666. __decorate([
  46667. BABYLON.serializeAsVector3()
  46668. ], FreeCamera.prototype, "ellipsoid", void 0);
  46669. __decorate([
  46670. BABYLON.serializeAsVector3()
  46671. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46672. __decorate([
  46673. BABYLON.serialize()
  46674. ], FreeCamera.prototype, "checkCollisions", void 0);
  46675. __decorate([
  46676. BABYLON.serialize()
  46677. ], FreeCamera.prototype, "applyGravity", void 0);
  46678. return FreeCamera;
  46679. }(BABYLON.TargetCamera));
  46680. BABYLON.FreeCamera = FreeCamera;
  46681. })(BABYLON || (BABYLON = {}));
  46682. //# sourceMappingURL=babylon.freeCamera.js.map
  46683. var BABYLON;
  46684. (function (BABYLON) {
  46685. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46686. function ArcRotateCameraKeyboardMoveInput() {
  46687. this._keys = new Array();
  46688. this.keysUp = [38];
  46689. this.keysDown = [40];
  46690. this.keysLeft = [37];
  46691. this.keysRight = [39];
  46692. this.keysReset = [220];
  46693. this.panningSensibility = 50.0;
  46694. this.zoomingSensibility = 25.0;
  46695. this.useAltToZoom = true;
  46696. }
  46697. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46698. var _this = this;
  46699. if (this._onCanvasBlurObserver) {
  46700. return;
  46701. }
  46702. this._scene = this.camera.getScene();
  46703. this._engine = this._scene.getEngine();
  46704. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46705. _this._keys = [];
  46706. });
  46707. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46708. var evt = info.event;
  46709. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46710. _this._ctrlPressed = evt.ctrlKey;
  46711. _this._altPressed = evt.altKey;
  46712. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46713. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46714. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46715. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46716. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46717. var index = _this._keys.indexOf(evt.keyCode);
  46718. if (index === -1) {
  46719. _this._keys.push(evt.keyCode);
  46720. }
  46721. if (evt.preventDefault) {
  46722. if (!noPreventDefault) {
  46723. evt.preventDefault();
  46724. }
  46725. }
  46726. }
  46727. }
  46728. else {
  46729. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46730. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46731. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46732. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46733. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46734. var index = _this._keys.indexOf(evt.keyCode);
  46735. if (index >= 0) {
  46736. _this._keys.splice(index, 1);
  46737. }
  46738. if (evt.preventDefault) {
  46739. if (!noPreventDefault) {
  46740. evt.preventDefault();
  46741. }
  46742. }
  46743. }
  46744. }
  46745. });
  46746. };
  46747. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46748. if (this._scene) {
  46749. if (this._onKeyboardObserver) {
  46750. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46751. }
  46752. if (this._onCanvasBlurObserver) {
  46753. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46754. }
  46755. this._onKeyboardObserver = null;
  46756. this._onCanvasBlurObserver = null;
  46757. }
  46758. this._keys = [];
  46759. };
  46760. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46761. if (this._onKeyboardObserver) {
  46762. var camera = this.camera;
  46763. for (var index = 0; index < this._keys.length; index++) {
  46764. var keyCode = this._keys[index];
  46765. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46766. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46767. camera.inertialPanningX -= 1 / this.panningSensibility;
  46768. }
  46769. else {
  46770. camera.inertialAlphaOffset -= 0.01;
  46771. }
  46772. }
  46773. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46774. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46775. camera.inertialPanningY += 1 / this.panningSensibility;
  46776. }
  46777. else if (this._altPressed && this.useAltToZoom) {
  46778. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46779. }
  46780. else {
  46781. camera.inertialBetaOffset -= 0.01;
  46782. }
  46783. }
  46784. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46785. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46786. camera.inertialPanningX += 1 / this.panningSensibility;
  46787. }
  46788. else {
  46789. camera.inertialAlphaOffset += 0.01;
  46790. }
  46791. }
  46792. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46793. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46794. camera.inertialPanningY -= 1 / this.panningSensibility;
  46795. }
  46796. else if (this._altPressed && this.useAltToZoom) {
  46797. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46798. }
  46799. else {
  46800. camera.inertialBetaOffset += 0.01;
  46801. }
  46802. }
  46803. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46804. camera.restoreState();
  46805. }
  46806. }
  46807. }
  46808. };
  46809. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46810. return "ArcRotateCameraKeyboardMoveInput";
  46811. };
  46812. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46813. return "keyboard";
  46814. };
  46815. __decorate([
  46816. BABYLON.serialize()
  46817. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46818. __decorate([
  46819. BABYLON.serialize()
  46820. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46821. __decorate([
  46822. BABYLON.serialize()
  46823. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46824. __decorate([
  46825. BABYLON.serialize()
  46826. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46827. __decorate([
  46828. BABYLON.serialize()
  46829. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46830. __decorate([
  46831. BABYLON.serialize()
  46832. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46833. __decorate([
  46834. BABYLON.serialize()
  46835. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46836. __decorate([
  46837. BABYLON.serialize()
  46838. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46839. return ArcRotateCameraKeyboardMoveInput;
  46840. }());
  46841. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46842. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46843. })(BABYLON || (BABYLON = {}));
  46844. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46845. var BABYLON;
  46846. (function (BABYLON) {
  46847. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46848. function ArcRotateCameraMouseWheelInput() {
  46849. this.wheelPrecision = 3.0;
  46850. /**
  46851. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46852. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46853. */
  46854. this.wheelDeltaPercentage = 0;
  46855. }
  46856. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46857. var _this = this;
  46858. this._wheel = function (p, s) {
  46859. //sanity check - this should be a PointerWheel event.
  46860. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46861. return;
  46862. var event = p.event;
  46863. var delta = 0;
  46864. if (event.wheelDelta) {
  46865. if (_this.wheelDeltaPercentage) {
  46866. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  46867. if (event.wheelDelta > 0) {
  46868. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  46869. }
  46870. else {
  46871. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  46872. }
  46873. }
  46874. else {
  46875. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  46876. }
  46877. }
  46878. else if (event.detail) {
  46879. delta = -event.detail / _this.wheelPrecision;
  46880. }
  46881. if (delta)
  46882. _this.camera.inertialRadiusOffset += delta;
  46883. if (event.preventDefault) {
  46884. if (!noPreventDefault) {
  46885. event.preventDefault();
  46886. }
  46887. }
  46888. };
  46889. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  46890. };
  46891. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  46892. if (this._observer && element) {
  46893. this.camera.getScene().onPointerObservable.remove(this._observer);
  46894. this._observer = null;
  46895. this._wheel = null;
  46896. }
  46897. };
  46898. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  46899. return "ArcRotateCameraMouseWheelInput";
  46900. };
  46901. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  46902. return "mousewheel";
  46903. };
  46904. __decorate([
  46905. BABYLON.serialize()
  46906. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  46907. __decorate([
  46908. BABYLON.serialize()
  46909. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  46910. return ArcRotateCameraMouseWheelInput;
  46911. }());
  46912. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  46913. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  46914. })(BABYLON || (BABYLON = {}));
  46915. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  46916. var BABYLON;
  46917. (function (BABYLON) {
  46918. var ArcRotateCameraPointersInput = /** @class */ (function () {
  46919. function ArcRotateCameraPointersInput() {
  46920. this.buttons = [0, 1, 2];
  46921. this.angularSensibilityX = 1000.0;
  46922. this.angularSensibilityY = 1000.0;
  46923. this.pinchPrecision = 12.0;
  46924. /**
  46925. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  46926. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  46927. */
  46928. this.pinchDeltaPercentage = 0;
  46929. this.panningSensibility = 1000.0;
  46930. this.multiTouchPanning = true;
  46931. this.multiTouchPanAndZoom = true;
  46932. this._isPanClick = false;
  46933. this.pinchInwards = true;
  46934. }
  46935. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  46936. var _this = this;
  46937. var engine = this.camera.getEngine();
  46938. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  46939. var pointA = null;
  46940. var pointB = null;
  46941. var previousPinchSquaredDistance = 0;
  46942. var initialDistance = 0;
  46943. var twoFingerActivityCount = 0;
  46944. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  46945. this._pointerInput = function (p, s) {
  46946. var evt = p.event;
  46947. var isTouch = p.event.pointerType === "touch";
  46948. if (engine.isInVRExclusivePointerMode) {
  46949. return;
  46950. }
  46951. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46952. return;
  46953. }
  46954. var srcElement = (evt.srcElement || evt.target);
  46955. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46956. try {
  46957. srcElement.setPointerCapture(evt.pointerId);
  46958. }
  46959. catch (e) {
  46960. //Nothing to do with the error. Execution will continue.
  46961. }
  46962. // Manage panning with pan button click
  46963. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  46964. // manage pointers
  46965. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  46966. if (pointA === null) {
  46967. pointA = cacheSoloPointer;
  46968. }
  46969. else if (pointB === null) {
  46970. pointB = cacheSoloPointer;
  46971. }
  46972. if (!noPreventDefault) {
  46973. evt.preventDefault();
  46974. element.focus();
  46975. }
  46976. }
  46977. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  46978. _this.camera.restoreState();
  46979. }
  46980. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46981. try {
  46982. srcElement.releasePointerCapture(evt.pointerId);
  46983. }
  46984. catch (e) {
  46985. //Nothing to do with the error.
  46986. }
  46987. cacheSoloPointer = null;
  46988. previousPinchSquaredDistance = 0;
  46989. previousMultiTouchPanPosition.isPaning = false;
  46990. previousMultiTouchPanPosition.isPinching = false;
  46991. twoFingerActivityCount = 0;
  46992. initialDistance = 0;
  46993. if (!isTouch) {
  46994. pointB = null; // Mouse and pen are mono pointer
  46995. }
  46996. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  46997. //but emptying completly pointers collection is required to fix a bug on iPhone :
  46998. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  46999. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47000. if (engine._badOS) {
  47001. pointA = pointB = null;
  47002. }
  47003. else {
  47004. //only remove the impacted pointer in case of multitouch allowing on most
  47005. //platforms switching from rotate to zoom and pan seamlessly.
  47006. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47007. pointA = pointB;
  47008. pointB = null;
  47009. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47010. }
  47011. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47012. pointB = null;
  47013. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47014. }
  47015. else {
  47016. pointA = pointB = null;
  47017. }
  47018. }
  47019. if (!noPreventDefault) {
  47020. evt.preventDefault();
  47021. }
  47022. }
  47023. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47024. if (!noPreventDefault) {
  47025. evt.preventDefault();
  47026. }
  47027. // One button down
  47028. if (pointA && pointB === null && cacheSoloPointer) {
  47029. if (_this.panningSensibility !== 0 &&
  47030. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47031. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47032. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47033. }
  47034. else {
  47035. var offsetX = evt.clientX - cacheSoloPointer.x;
  47036. var offsetY = evt.clientY - cacheSoloPointer.y;
  47037. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47038. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47039. }
  47040. cacheSoloPointer.x = evt.clientX;
  47041. cacheSoloPointer.y = evt.clientY;
  47042. }
  47043. // Two buttons down: pinch/pan
  47044. else if (pointA && pointB) {
  47045. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47046. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47047. ed.x = evt.clientX;
  47048. ed.y = evt.clientY;
  47049. var direction = _this.pinchInwards ? 1 : -1;
  47050. var distX = pointA.x - pointB.x;
  47051. var distY = pointA.y - pointB.y;
  47052. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47053. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47054. if (previousPinchSquaredDistance === 0) {
  47055. initialDistance = pinchDistance;
  47056. previousPinchSquaredDistance = pinchSquaredDistance;
  47057. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47058. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47059. return;
  47060. }
  47061. if (_this.multiTouchPanAndZoom) {
  47062. if (_this.pinchDeltaPercentage) {
  47063. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47064. }
  47065. else {
  47066. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47067. (_this.pinchPrecision *
  47068. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47069. direction);
  47070. }
  47071. if (_this.panningSensibility !== 0) {
  47072. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47073. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47074. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47075. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47076. previousMultiTouchPanPosition.x = pointersCenterX;
  47077. previousMultiTouchPanPosition.y = pointersCenterY;
  47078. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47079. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47080. }
  47081. }
  47082. else {
  47083. twoFingerActivityCount++;
  47084. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47085. if (_this.pinchDeltaPercentage) {
  47086. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47087. }
  47088. else {
  47089. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47090. (_this.pinchPrecision *
  47091. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47092. direction);
  47093. }
  47094. previousMultiTouchPanPosition.isPaning = false;
  47095. previousMultiTouchPanPosition.isPinching = true;
  47096. }
  47097. else {
  47098. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47099. if (!previousMultiTouchPanPosition.isPaning) {
  47100. previousMultiTouchPanPosition.isPaning = true;
  47101. previousMultiTouchPanPosition.isPinching = false;
  47102. previousMultiTouchPanPosition.x = ed.x;
  47103. previousMultiTouchPanPosition.y = ed.y;
  47104. return;
  47105. }
  47106. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47107. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47108. }
  47109. }
  47110. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47111. previousMultiTouchPanPosition.x = ed.x;
  47112. previousMultiTouchPanPosition.y = ed.y;
  47113. }
  47114. }
  47115. previousPinchSquaredDistance = pinchSquaredDistance;
  47116. }
  47117. }
  47118. };
  47119. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47120. this._onContextMenu = function (evt) {
  47121. evt.preventDefault();
  47122. };
  47123. if (!this.camera._useCtrlForPanning) {
  47124. element.addEventListener("contextmenu", this._onContextMenu, false);
  47125. }
  47126. this._onLostFocus = function () {
  47127. //this._keys = [];
  47128. pointA = pointB = null;
  47129. previousPinchSquaredDistance = 0;
  47130. previousMultiTouchPanPosition.isPaning = false;
  47131. previousMultiTouchPanPosition.isPinching = false;
  47132. twoFingerActivityCount = 0;
  47133. cacheSoloPointer = null;
  47134. initialDistance = 0;
  47135. };
  47136. this._onMouseMove = function (evt) {
  47137. if (!engine.isPointerLock) {
  47138. return;
  47139. }
  47140. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47141. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47142. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47143. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47144. if (!noPreventDefault) {
  47145. evt.preventDefault();
  47146. }
  47147. };
  47148. this._onGestureStart = function (e) {
  47149. if (window.MSGesture === undefined) {
  47150. return;
  47151. }
  47152. if (!_this._MSGestureHandler) {
  47153. _this._MSGestureHandler = new MSGesture();
  47154. _this._MSGestureHandler.target = element;
  47155. }
  47156. _this._MSGestureHandler.addPointer(e.pointerId);
  47157. };
  47158. this._onGesture = function (e) {
  47159. _this.camera.radius *= e.scale;
  47160. if (e.preventDefault) {
  47161. if (!noPreventDefault) {
  47162. e.stopPropagation();
  47163. e.preventDefault();
  47164. }
  47165. }
  47166. };
  47167. element.addEventListener("mousemove", this._onMouseMove, false);
  47168. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47169. element.addEventListener("MSGestureChange", this._onGesture, false);
  47170. BABYLON.Tools.RegisterTopRootEvents([
  47171. { name: "blur", handler: this._onLostFocus }
  47172. ]);
  47173. };
  47174. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47175. if (this._onLostFocus) {
  47176. BABYLON.Tools.UnregisterTopRootEvents([
  47177. { name: "blur", handler: this._onLostFocus }
  47178. ]);
  47179. }
  47180. if (element && this._observer) {
  47181. this.camera.getScene().onPointerObservable.remove(this._observer);
  47182. this._observer = null;
  47183. if (this._onContextMenu) {
  47184. element.removeEventListener("contextmenu", this._onContextMenu);
  47185. }
  47186. if (this._onMouseMove) {
  47187. element.removeEventListener("mousemove", this._onMouseMove);
  47188. }
  47189. if (this._onGestureStart) {
  47190. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47191. }
  47192. if (this._onGesture) {
  47193. element.removeEventListener("MSGestureChange", this._onGesture);
  47194. }
  47195. this._isPanClick = false;
  47196. this.pinchInwards = true;
  47197. this._onMouseMove = null;
  47198. this._onGestureStart = null;
  47199. this._onGesture = null;
  47200. this._MSGestureHandler = null;
  47201. this._onLostFocus = null;
  47202. this._onContextMenu = null;
  47203. }
  47204. };
  47205. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47206. return "ArcRotateCameraPointersInput";
  47207. };
  47208. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47209. return "pointers";
  47210. };
  47211. __decorate([
  47212. BABYLON.serialize()
  47213. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47214. __decorate([
  47215. BABYLON.serialize()
  47216. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47217. __decorate([
  47218. BABYLON.serialize()
  47219. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47220. __decorate([
  47221. BABYLON.serialize()
  47222. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47223. __decorate([
  47224. BABYLON.serialize()
  47225. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47226. __decorate([
  47227. BABYLON.serialize()
  47228. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47229. __decorate([
  47230. BABYLON.serialize()
  47231. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47232. __decorate([
  47233. BABYLON.serialize()
  47234. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47235. return ArcRotateCameraPointersInput;
  47236. }());
  47237. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47238. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47239. })(BABYLON || (BABYLON = {}));
  47240. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47241. var BABYLON;
  47242. (function (BABYLON) {
  47243. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47244. __extends(ArcRotateCameraInputsManager, _super);
  47245. function ArcRotateCameraInputsManager(camera) {
  47246. return _super.call(this, camera) || this;
  47247. }
  47248. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47249. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47250. return this;
  47251. };
  47252. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47253. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47254. return this;
  47255. };
  47256. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47257. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47258. return this;
  47259. };
  47260. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47261. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47262. return this;
  47263. };
  47264. return ArcRotateCameraInputsManager;
  47265. }(BABYLON.CameraInputsManager));
  47266. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47267. })(BABYLON || (BABYLON = {}));
  47268. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47269. var BABYLON;
  47270. (function (BABYLON) {
  47271. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47272. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47273. });
  47274. var ArcRotateCamera = /** @class */ (function (_super) {
  47275. __extends(ArcRotateCamera, _super);
  47276. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47277. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47278. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47279. _this.inertialAlphaOffset = 0;
  47280. _this.inertialBetaOffset = 0;
  47281. _this.inertialRadiusOffset = 0;
  47282. _this.lowerAlphaLimit = null;
  47283. _this.upperAlphaLimit = null;
  47284. _this.lowerBetaLimit = 0.01;
  47285. _this.upperBetaLimit = Math.PI;
  47286. _this.lowerRadiusLimit = null;
  47287. _this.upperRadiusLimit = null;
  47288. _this.inertialPanningX = 0;
  47289. _this.inertialPanningY = 0;
  47290. _this.pinchToPanMaxDistance = 20;
  47291. _this.panningDistanceLimit = null;
  47292. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47293. _this.panningInertia = 0.9;
  47294. //-- end properties for backward compatibility for inputs
  47295. _this.zoomOnFactor = 1;
  47296. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47297. _this.allowUpsideDown = true;
  47298. _this._viewMatrix = new BABYLON.Matrix();
  47299. // Panning
  47300. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47301. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47302. _this.checkCollisions = false;
  47303. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47304. _this._previousPosition = BABYLON.Vector3.Zero();
  47305. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47306. _this._newPosition = BABYLON.Vector3.Zero();
  47307. _this._computationVector = BABYLON.Vector3.Zero();
  47308. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47309. if (collidedMesh === void 0) { collidedMesh = null; }
  47310. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47311. newPosition.multiplyInPlace(_this._collider._radius);
  47312. }
  47313. if (!collidedMesh) {
  47314. _this._previousPosition.copyFrom(_this.position);
  47315. }
  47316. else {
  47317. _this.setPosition(newPosition);
  47318. if (_this.onCollide) {
  47319. _this.onCollide(collidedMesh);
  47320. }
  47321. }
  47322. // Recompute because of constraints
  47323. var cosa = Math.cos(_this.alpha);
  47324. var sina = Math.sin(_this.alpha);
  47325. var cosb = Math.cos(_this.beta);
  47326. var sinb = Math.sin(_this.beta);
  47327. if (sinb === 0) {
  47328. sinb = 0.0001;
  47329. }
  47330. var target = _this._getTargetPosition();
  47331. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47332. target.addToRef(_this._computationVector, _this._newPosition);
  47333. _this.position.copyFrom(_this._newPosition);
  47334. var up = _this.upVector;
  47335. if (_this.allowUpsideDown && _this.beta < 0) {
  47336. up = up.clone();
  47337. up = up.negate();
  47338. }
  47339. _this._computeViewMatrix(_this.position, target, up);
  47340. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47341. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47342. _this._collisionTriggered = false;
  47343. };
  47344. _this._target = BABYLON.Vector3.Zero();
  47345. if (target) {
  47346. _this.setTarget(target);
  47347. }
  47348. _this.alpha = alpha;
  47349. _this.beta = beta;
  47350. _this.radius = radius;
  47351. _this.getViewMatrix();
  47352. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47353. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47354. return _this;
  47355. }
  47356. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47357. get: function () {
  47358. return this._target;
  47359. },
  47360. set: function (value) {
  47361. this.setTarget(value);
  47362. },
  47363. enumerable: true,
  47364. configurable: true
  47365. });
  47366. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47367. //-- begin properties for backward compatibility for inputs
  47368. get: function () {
  47369. var pointers = this.inputs.attached["pointers"];
  47370. if (pointers)
  47371. return pointers.angularSensibilityX;
  47372. return 0;
  47373. },
  47374. set: function (value) {
  47375. var pointers = this.inputs.attached["pointers"];
  47376. if (pointers) {
  47377. pointers.angularSensibilityX = value;
  47378. }
  47379. },
  47380. enumerable: true,
  47381. configurable: true
  47382. });
  47383. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47384. get: function () {
  47385. var pointers = this.inputs.attached["pointers"];
  47386. if (pointers)
  47387. return pointers.angularSensibilityY;
  47388. return 0;
  47389. },
  47390. set: function (value) {
  47391. var pointers = this.inputs.attached["pointers"];
  47392. if (pointers) {
  47393. pointers.angularSensibilityY = value;
  47394. }
  47395. },
  47396. enumerable: true,
  47397. configurable: true
  47398. });
  47399. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47400. get: function () {
  47401. var pointers = this.inputs.attached["pointers"];
  47402. if (pointers)
  47403. return pointers.pinchPrecision;
  47404. return 0;
  47405. },
  47406. set: function (value) {
  47407. var pointers = this.inputs.attached["pointers"];
  47408. if (pointers) {
  47409. pointers.pinchPrecision = value;
  47410. }
  47411. },
  47412. enumerable: true,
  47413. configurable: true
  47414. });
  47415. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47416. get: function () {
  47417. var pointers = this.inputs.attached["pointers"];
  47418. if (pointers)
  47419. return pointers.pinchDeltaPercentage;
  47420. return 0;
  47421. },
  47422. set: function (value) {
  47423. var pointers = this.inputs.attached["pointers"];
  47424. if (pointers) {
  47425. pointers.pinchDeltaPercentage = value;
  47426. }
  47427. },
  47428. enumerable: true,
  47429. configurable: true
  47430. });
  47431. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47432. get: function () {
  47433. var pointers = this.inputs.attached["pointers"];
  47434. if (pointers)
  47435. return pointers.panningSensibility;
  47436. return 0;
  47437. },
  47438. set: function (value) {
  47439. var pointers = this.inputs.attached["pointers"];
  47440. if (pointers) {
  47441. pointers.panningSensibility = value;
  47442. }
  47443. },
  47444. enumerable: true,
  47445. configurable: true
  47446. });
  47447. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47448. get: function () {
  47449. var keyboard = this.inputs.attached["keyboard"];
  47450. if (keyboard)
  47451. return keyboard.keysUp;
  47452. return [];
  47453. },
  47454. set: function (value) {
  47455. var keyboard = this.inputs.attached["keyboard"];
  47456. if (keyboard)
  47457. keyboard.keysUp = value;
  47458. },
  47459. enumerable: true,
  47460. configurable: true
  47461. });
  47462. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47463. get: function () {
  47464. var keyboard = this.inputs.attached["keyboard"];
  47465. if (keyboard)
  47466. return keyboard.keysDown;
  47467. return [];
  47468. },
  47469. set: function (value) {
  47470. var keyboard = this.inputs.attached["keyboard"];
  47471. if (keyboard)
  47472. keyboard.keysDown = value;
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47478. get: function () {
  47479. var keyboard = this.inputs.attached["keyboard"];
  47480. if (keyboard)
  47481. return keyboard.keysLeft;
  47482. return [];
  47483. },
  47484. set: function (value) {
  47485. var keyboard = this.inputs.attached["keyboard"];
  47486. if (keyboard)
  47487. keyboard.keysLeft = value;
  47488. },
  47489. enumerable: true,
  47490. configurable: true
  47491. });
  47492. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47493. get: function () {
  47494. var keyboard = this.inputs.attached["keyboard"];
  47495. if (keyboard)
  47496. return keyboard.keysRight;
  47497. return [];
  47498. },
  47499. set: function (value) {
  47500. var keyboard = this.inputs.attached["keyboard"];
  47501. if (keyboard)
  47502. keyboard.keysRight = value;
  47503. },
  47504. enumerable: true,
  47505. configurable: true
  47506. });
  47507. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47508. get: function () {
  47509. var mousewheel = this.inputs.attached["mousewheel"];
  47510. if (mousewheel)
  47511. return mousewheel.wheelPrecision;
  47512. return 0;
  47513. },
  47514. set: function (value) {
  47515. var mousewheel = this.inputs.attached["mousewheel"];
  47516. if (mousewheel)
  47517. mousewheel.wheelPrecision = value;
  47518. },
  47519. enumerable: true,
  47520. configurable: true
  47521. });
  47522. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47523. get: function () {
  47524. var mousewheel = this.inputs.attached["mousewheel"];
  47525. if (mousewheel)
  47526. return mousewheel.wheelDeltaPercentage;
  47527. return 0;
  47528. },
  47529. set: function (value) {
  47530. var mousewheel = this.inputs.attached["mousewheel"];
  47531. if (mousewheel)
  47532. mousewheel.wheelDeltaPercentage = value;
  47533. },
  47534. enumerable: true,
  47535. configurable: true
  47536. });
  47537. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47538. get: function () {
  47539. return this._bouncingBehavior;
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47545. get: function () {
  47546. return this._bouncingBehavior != null;
  47547. },
  47548. set: function (value) {
  47549. if (value === this.useBouncingBehavior) {
  47550. return;
  47551. }
  47552. if (value) {
  47553. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47554. this.addBehavior(this._bouncingBehavior);
  47555. }
  47556. else if (this._bouncingBehavior) {
  47557. this.removeBehavior(this._bouncingBehavior);
  47558. this._bouncingBehavior = null;
  47559. }
  47560. },
  47561. enumerable: true,
  47562. configurable: true
  47563. });
  47564. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47565. get: function () {
  47566. return this._framingBehavior;
  47567. },
  47568. enumerable: true,
  47569. configurable: true
  47570. });
  47571. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47572. get: function () {
  47573. return this._framingBehavior != null;
  47574. },
  47575. set: function (value) {
  47576. if (value === this.useFramingBehavior) {
  47577. return;
  47578. }
  47579. if (value) {
  47580. this._framingBehavior = new BABYLON.FramingBehavior();
  47581. this.addBehavior(this._framingBehavior);
  47582. }
  47583. else if (this._framingBehavior) {
  47584. this.removeBehavior(this._framingBehavior);
  47585. this._framingBehavior = null;
  47586. }
  47587. },
  47588. enumerable: true,
  47589. configurable: true
  47590. });
  47591. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47592. get: function () {
  47593. return this._autoRotationBehavior;
  47594. },
  47595. enumerable: true,
  47596. configurable: true
  47597. });
  47598. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47599. get: function () {
  47600. return this._autoRotationBehavior != null;
  47601. },
  47602. set: function (value) {
  47603. if (value === this.useAutoRotationBehavior) {
  47604. return;
  47605. }
  47606. if (value) {
  47607. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47608. this.addBehavior(this._autoRotationBehavior);
  47609. }
  47610. else if (this._autoRotationBehavior) {
  47611. this.removeBehavior(this._autoRotationBehavior);
  47612. this._autoRotationBehavior = null;
  47613. }
  47614. },
  47615. enumerable: true,
  47616. configurable: true
  47617. });
  47618. // Cache
  47619. ArcRotateCamera.prototype._initCache = function () {
  47620. _super.prototype._initCache.call(this);
  47621. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47622. this._cache.alpha = undefined;
  47623. this._cache.beta = undefined;
  47624. this._cache.radius = undefined;
  47625. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47626. };
  47627. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47628. if (!ignoreParentClass) {
  47629. _super.prototype._updateCache.call(this);
  47630. }
  47631. this._cache._target.copyFrom(this._getTargetPosition());
  47632. this._cache.alpha = this.alpha;
  47633. this._cache.beta = this.beta;
  47634. this._cache.radius = this.radius;
  47635. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47636. };
  47637. ArcRotateCamera.prototype._getTargetPosition = function () {
  47638. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47639. var pos = this._targetHost.getAbsolutePosition();
  47640. if (this._targetBoundingCenter) {
  47641. pos.addToRef(this._targetBoundingCenter, this._target);
  47642. }
  47643. else {
  47644. this._target.copyFrom(pos);
  47645. }
  47646. }
  47647. var lockedTargetPosition = this._getLockedTargetPosition();
  47648. if (lockedTargetPosition) {
  47649. return lockedTargetPosition;
  47650. }
  47651. return this._target;
  47652. };
  47653. ArcRotateCamera.prototype.storeState = function () {
  47654. this._storedAlpha = this.alpha;
  47655. this._storedBeta = this.beta;
  47656. this._storedRadius = this.radius;
  47657. this._storedTarget = this._getTargetPosition().clone();
  47658. return _super.prototype.storeState.call(this);
  47659. };
  47660. /**
  47661. * Restored camera state. You must call storeState() first
  47662. */
  47663. ArcRotateCamera.prototype._restoreStateValues = function () {
  47664. if (!_super.prototype._restoreStateValues.call(this)) {
  47665. return false;
  47666. }
  47667. this.alpha = this._storedAlpha;
  47668. this.beta = this._storedBeta;
  47669. this.radius = this._storedRadius;
  47670. this.setTarget(this._storedTarget.clone());
  47671. this.inertialAlphaOffset = 0;
  47672. this.inertialBetaOffset = 0;
  47673. this.inertialRadiusOffset = 0;
  47674. this.inertialPanningX = 0;
  47675. this.inertialPanningY = 0;
  47676. return true;
  47677. };
  47678. // Synchronized
  47679. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47680. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47681. return false;
  47682. return this._cache._target.equals(this._getTargetPosition())
  47683. && this._cache.alpha === this.alpha
  47684. && this._cache.beta === this.beta
  47685. && this._cache.radius === this.radius
  47686. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47687. };
  47688. // Methods
  47689. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47690. var _this = this;
  47691. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47692. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47693. this._useCtrlForPanning = useCtrlForPanning;
  47694. this._panningMouseButton = panningMouseButton;
  47695. this.inputs.attachElement(element, noPreventDefault);
  47696. this._reset = function () {
  47697. _this.inertialAlphaOffset = 0;
  47698. _this.inertialBetaOffset = 0;
  47699. _this.inertialRadiusOffset = 0;
  47700. _this.inertialPanningX = 0;
  47701. _this.inertialPanningY = 0;
  47702. };
  47703. };
  47704. ArcRotateCamera.prototype.detachControl = function (element) {
  47705. this.inputs.detachElement(element);
  47706. if (this._reset) {
  47707. this._reset();
  47708. }
  47709. };
  47710. ArcRotateCamera.prototype._checkInputs = function () {
  47711. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47712. if (this._collisionTriggered) {
  47713. return;
  47714. }
  47715. this.inputs.checkInputs();
  47716. // Inertia
  47717. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47718. var inertialAlphaOffset = this.inertialAlphaOffset;
  47719. if (this.beta <= 0)
  47720. inertialAlphaOffset *= -1;
  47721. if (this.getScene().useRightHandedSystem)
  47722. inertialAlphaOffset *= -1;
  47723. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47724. inertialAlphaOffset *= -1;
  47725. this.alpha += inertialAlphaOffset;
  47726. this.beta += this.inertialBetaOffset;
  47727. this.radius -= this.inertialRadiusOffset;
  47728. this.inertialAlphaOffset *= this.inertia;
  47729. this.inertialBetaOffset *= this.inertia;
  47730. this.inertialRadiusOffset *= this.inertia;
  47731. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47732. this.inertialAlphaOffset = 0;
  47733. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47734. this.inertialBetaOffset = 0;
  47735. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47736. this.inertialRadiusOffset = 0;
  47737. }
  47738. // Panning inertia
  47739. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47740. if (!this._localDirection) {
  47741. this._localDirection = BABYLON.Vector3.Zero();
  47742. this._transformedDirection = BABYLON.Vector3.Zero();
  47743. }
  47744. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47745. this._localDirection.multiplyInPlace(this.panningAxis);
  47746. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47747. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47748. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47749. if (!this.panningAxis.y) {
  47750. this._transformedDirection.y = 0;
  47751. }
  47752. if (!this._targetHost) {
  47753. if (this.panningDistanceLimit) {
  47754. this._transformedDirection.addInPlace(this._target);
  47755. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47756. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47757. this._target.copyFrom(this._transformedDirection);
  47758. }
  47759. }
  47760. else {
  47761. this._target.addInPlace(this._transformedDirection);
  47762. }
  47763. }
  47764. this.inertialPanningX *= this.panningInertia;
  47765. this.inertialPanningY *= this.panningInertia;
  47766. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47767. this.inertialPanningX = 0;
  47768. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47769. this.inertialPanningY = 0;
  47770. }
  47771. // Limits
  47772. this._checkLimits();
  47773. _super.prototype._checkInputs.call(this);
  47774. };
  47775. ArcRotateCamera.prototype._checkLimits = function () {
  47776. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47777. if (this.allowUpsideDown && this.beta > Math.PI) {
  47778. this.beta = this.beta - (2 * Math.PI);
  47779. }
  47780. }
  47781. else {
  47782. if (this.beta < this.lowerBetaLimit) {
  47783. this.beta = this.lowerBetaLimit;
  47784. }
  47785. }
  47786. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47787. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47788. this.beta = this.beta + (2 * Math.PI);
  47789. }
  47790. }
  47791. else {
  47792. if (this.beta > this.upperBetaLimit) {
  47793. this.beta = this.upperBetaLimit;
  47794. }
  47795. }
  47796. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  47797. this.alpha = this.lowerAlphaLimit;
  47798. }
  47799. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  47800. this.alpha = this.upperAlphaLimit;
  47801. }
  47802. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  47803. this.radius = this.lowerRadiusLimit;
  47804. }
  47805. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  47806. this.radius = this.upperRadiusLimit;
  47807. }
  47808. };
  47809. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47810. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47811. this.radius = this._computationVector.length();
  47812. if (this.radius === 0) {
  47813. this.radius = 0.0001; // Just to avoid division by zero
  47814. }
  47815. // Alpha
  47816. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47817. if (this._computationVector.z < 0) {
  47818. this.alpha = 2 * Math.PI - this.alpha;
  47819. }
  47820. // Beta
  47821. this.beta = Math.acos(this._computationVector.y / this.radius);
  47822. this._checkLimits();
  47823. };
  47824. ArcRotateCamera.prototype.setPosition = function (position) {
  47825. if (this.position.equals(position)) {
  47826. return;
  47827. }
  47828. this.position.copyFrom(position);
  47829. this.rebuildAnglesAndRadius();
  47830. };
  47831. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47832. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47833. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47834. if (target.getBoundingInfo) {
  47835. if (toBoundingCenter) {
  47836. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47837. }
  47838. else {
  47839. this._targetBoundingCenter = null;
  47840. }
  47841. this._targetHost = target;
  47842. this._target = this._getTargetPosition();
  47843. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47844. }
  47845. else {
  47846. var newTarget = target;
  47847. var currentTarget = this._getTargetPosition();
  47848. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47849. return;
  47850. }
  47851. this._targetHost = null;
  47852. this._target = newTarget;
  47853. this._targetBoundingCenter = null;
  47854. this.onMeshTargetChangedObservable.notifyObservers(null);
  47855. }
  47856. this.rebuildAnglesAndRadius();
  47857. };
  47858. ArcRotateCamera.prototype._getViewMatrix = function () {
  47859. // Compute
  47860. var cosa = Math.cos(this.alpha);
  47861. var sina = Math.sin(this.alpha);
  47862. var cosb = Math.cos(this.beta);
  47863. var sinb = Math.sin(this.beta);
  47864. if (sinb === 0) {
  47865. sinb = 0.0001;
  47866. }
  47867. var target = this._getTargetPosition();
  47868. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  47869. target.addToRef(this._computationVector, this._newPosition);
  47870. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  47871. if (!this._collider) {
  47872. this._collider = new BABYLON.Collider();
  47873. }
  47874. this._collider._radius = this.collisionRadius;
  47875. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  47876. this._collisionTriggered = true;
  47877. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47878. }
  47879. else {
  47880. this.position.copyFrom(this._newPosition);
  47881. var up = this.upVector;
  47882. if (this.allowUpsideDown && sinb < 0) {
  47883. up = up.clone();
  47884. up = up.negate();
  47885. }
  47886. this._computeViewMatrix(this.position, target, up);
  47887. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  47888. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  47889. }
  47890. this._currentTarget = target;
  47891. return this._viewMatrix;
  47892. };
  47893. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  47894. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47895. meshes = meshes || this.getScene().meshes;
  47896. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  47897. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  47898. this.radius = distance * this.zoomOnFactor;
  47899. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  47900. };
  47901. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  47902. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  47903. var meshesOrMinMaxVector;
  47904. var distance;
  47905. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  47906. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  47907. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  47908. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  47909. }
  47910. else { //minMaxVector and distance
  47911. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  47912. meshesOrMinMaxVector = minMaxVectorAndDistance;
  47913. distance = minMaxVectorAndDistance.distance;
  47914. }
  47915. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  47916. if (!doNotUpdateMaxZ) {
  47917. this.maxZ = distance * 2;
  47918. }
  47919. };
  47920. /**
  47921. * @override
  47922. * Override Camera.createRigCamera
  47923. */
  47924. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47925. var alphaShift = 0;
  47926. switch (this.cameraRigMode) {
  47927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47930. case BABYLON.Camera.RIG_MODE_VR:
  47931. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  47932. break;
  47933. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47934. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  47935. break;
  47936. }
  47937. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  47938. rigCam._cameraRigParams = {};
  47939. return rigCam;
  47940. };
  47941. /**
  47942. * @override
  47943. * Override Camera._updateRigCameras
  47944. */
  47945. ArcRotateCamera.prototype._updateRigCameras = function () {
  47946. var camLeft = this._rigCameras[0];
  47947. var camRight = this._rigCameras[1];
  47948. camLeft.beta = camRight.beta = this.beta;
  47949. camLeft.radius = camRight.radius = this.radius;
  47950. switch (this.cameraRigMode) {
  47951. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47952. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47953. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47954. case BABYLON.Camera.RIG_MODE_VR:
  47955. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47956. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47957. break;
  47958. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47959. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  47960. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  47961. break;
  47962. }
  47963. _super.prototype._updateRigCameras.call(this);
  47964. };
  47965. ArcRotateCamera.prototype.dispose = function () {
  47966. this.inputs.clear();
  47967. _super.prototype.dispose.call(this);
  47968. };
  47969. ArcRotateCamera.prototype.getClassName = function () {
  47970. return "ArcRotateCamera";
  47971. };
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], ArcRotateCamera.prototype, "alpha", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], ArcRotateCamera.prototype, "beta", void 0);
  47978. __decorate([
  47979. BABYLON.serialize()
  47980. ], ArcRotateCamera.prototype, "radius", void 0);
  47981. __decorate([
  47982. BABYLON.serializeAsVector3("target")
  47983. ], ArcRotateCamera.prototype, "_target", void 0);
  47984. __decorate([
  47985. BABYLON.serialize()
  47986. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  47987. __decorate([
  47988. BABYLON.serialize()
  47989. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  47990. __decorate([
  47991. BABYLON.serialize()
  47992. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  47993. __decorate([
  47994. BABYLON.serialize()
  47995. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  47996. __decorate([
  47997. BABYLON.serialize()
  47998. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  47999. __decorate([
  48000. BABYLON.serialize()
  48001. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48002. __decorate([
  48003. BABYLON.serialize()
  48004. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48005. __decorate([
  48006. BABYLON.serialize()
  48007. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48008. __decorate([
  48009. BABYLON.serialize()
  48010. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48011. __decorate([
  48012. BABYLON.serialize()
  48013. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48014. __decorate([
  48015. BABYLON.serialize()
  48016. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48017. __decorate([
  48018. BABYLON.serialize()
  48019. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48020. __decorate([
  48021. BABYLON.serialize()
  48022. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48023. __decorate([
  48024. BABYLON.serializeAsVector3()
  48025. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48026. __decorate([
  48027. BABYLON.serialize()
  48028. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48029. __decorate([
  48030. BABYLON.serialize()
  48031. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48032. __decorate([
  48033. BABYLON.serialize()
  48034. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48035. return ArcRotateCamera;
  48036. }(BABYLON.TargetCamera));
  48037. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48038. })(BABYLON || (BABYLON = {}));
  48039. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48040. var BABYLON;
  48041. (function (BABYLON) {
  48042. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48043. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48044. });
  48045. /**
  48046. * The HemisphericLight simulates the ambient environment light,
  48047. * so the passed direction is the light reflection direction, not the incoming direction.
  48048. */
  48049. var HemisphericLight = /** @class */ (function (_super) {
  48050. __extends(HemisphericLight, _super);
  48051. /**
  48052. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48053. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48054. * The HemisphericLight can't cast shadows.
  48055. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48056. * @param name The friendly name of the light
  48057. * @param direction The direction of the light reflection
  48058. * @param scene The scene the light belongs to
  48059. */
  48060. function HemisphericLight(name, direction, scene) {
  48061. var _this = _super.call(this, name, scene) || this;
  48062. /**
  48063. * The groundColor is the light in the opposite direction to the one specified during creation.
  48064. * 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.
  48065. */
  48066. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48067. _this.direction = direction || BABYLON.Vector3.Up();
  48068. return _this;
  48069. }
  48070. HemisphericLight.prototype._buildUniformLayout = function () {
  48071. this._uniformBuffer.addUniform("vLightData", 4);
  48072. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48073. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48074. this._uniformBuffer.addUniform("vLightGround", 3);
  48075. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48076. this._uniformBuffer.addUniform("depthValues", 2);
  48077. this._uniformBuffer.create();
  48078. };
  48079. /**
  48080. * Returns the string "HemisphericLight".
  48081. * @return The class name
  48082. */
  48083. HemisphericLight.prototype.getClassName = function () {
  48084. return "HemisphericLight";
  48085. };
  48086. /**
  48087. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48088. * Returns the updated direction.
  48089. * @param target The target the direction should point to
  48090. * @return The computed direction
  48091. */
  48092. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48093. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48094. return this.direction;
  48095. };
  48096. /**
  48097. * Returns the shadow generator associated to the light.
  48098. * @returns Always null for hemispheric lights because it does not support shadows.
  48099. */
  48100. HemisphericLight.prototype.getShadowGenerator = function () {
  48101. return null;
  48102. };
  48103. /**
  48104. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48105. * @param effect The effect to update
  48106. * @param lightIndex The index of the light in the effect to update
  48107. * @returns The hemispheric light
  48108. */
  48109. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48110. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48111. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48112. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48113. return this;
  48114. };
  48115. /**
  48116. * @hidden internal use only.
  48117. */
  48118. HemisphericLight.prototype._getWorldMatrix = function () {
  48119. if (!this._worldMatrix) {
  48120. this._worldMatrix = BABYLON.Matrix.Identity();
  48121. }
  48122. return this._worldMatrix;
  48123. };
  48124. /**
  48125. * Returns the integer 3.
  48126. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48127. */
  48128. HemisphericLight.prototype.getTypeID = function () {
  48129. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48130. };
  48131. /**
  48132. * Prepares the list of defines specific to the light type.
  48133. * @param defines the list of defines
  48134. * @param lightIndex defines the index of the light for the effect
  48135. */
  48136. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48137. defines["HEMILIGHT" + lightIndex] = true;
  48138. };
  48139. __decorate([
  48140. BABYLON.serializeAsColor3()
  48141. ], HemisphericLight.prototype, "groundColor", void 0);
  48142. __decorate([
  48143. BABYLON.serializeAsVector3()
  48144. ], HemisphericLight.prototype, "direction", void 0);
  48145. return HemisphericLight;
  48146. }(BABYLON.Light));
  48147. BABYLON.HemisphericLight = HemisphericLight;
  48148. })(BABYLON || (BABYLON = {}));
  48149. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48150. var BABYLON;
  48151. (function (BABYLON) {
  48152. /**
  48153. * Base implementation IShadowLight
  48154. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48155. */
  48156. var ShadowLight = /** @class */ (function (_super) {
  48157. __extends(ShadowLight, _super);
  48158. function ShadowLight() {
  48159. var _this = _super !== null && _super.apply(this, arguments) || this;
  48160. _this._needProjectionMatrixCompute = true;
  48161. return _this;
  48162. }
  48163. ShadowLight.prototype._setPosition = function (value) {
  48164. this._position = value;
  48165. };
  48166. Object.defineProperty(ShadowLight.prototype, "position", {
  48167. /**
  48168. * Sets the position the shadow will be casted from. Also use as the light position for both
  48169. * point and spot lights.
  48170. */
  48171. get: function () {
  48172. return this._position;
  48173. },
  48174. /**
  48175. * Sets the position the shadow will be casted from. Also use as the light position for both
  48176. * point and spot lights.
  48177. */
  48178. set: function (value) {
  48179. this._setPosition(value);
  48180. },
  48181. enumerable: true,
  48182. configurable: true
  48183. });
  48184. ShadowLight.prototype._setDirection = function (value) {
  48185. this._direction = value;
  48186. };
  48187. Object.defineProperty(ShadowLight.prototype, "direction", {
  48188. /**
  48189. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48190. * Also use as the light direction on spot and directional lights.
  48191. */
  48192. get: function () {
  48193. return this._direction;
  48194. },
  48195. /**
  48196. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48197. * Also use as the light direction on spot and directional lights.
  48198. */
  48199. set: function (value) {
  48200. this._setDirection(value);
  48201. },
  48202. enumerable: true,
  48203. configurable: true
  48204. });
  48205. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48206. /**
  48207. * Gets the shadow projection clipping minimum z value.
  48208. */
  48209. get: function () {
  48210. return this._shadowMinZ;
  48211. },
  48212. /**
  48213. * Sets the shadow projection clipping minimum z value.
  48214. */
  48215. set: function (value) {
  48216. this._shadowMinZ = value;
  48217. this.forceProjectionMatrixCompute();
  48218. },
  48219. enumerable: true,
  48220. configurable: true
  48221. });
  48222. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48223. /**
  48224. * Sets the shadow projection clipping maximum z value.
  48225. */
  48226. get: function () {
  48227. return this._shadowMaxZ;
  48228. },
  48229. /**
  48230. * Gets the shadow projection clipping maximum z value.
  48231. */
  48232. set: function (value) {
  48233. this._shadowMaxZ = value;
  48234. this.forceProjectionMatrixCompute();
  48235. },
  48236. enumerable: true,
  48237. configurable: true
  48238. });
  48239. /**
  48240. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48241. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48242. */
  48243. ShadowLight.prototype.computeTransformedInformation = function () {
  48244. if (this.parent && this.parent.getWorldMatrix) {
  48245. if (!this.transformedPosition) {
  48246. this.transformedPosition = BABYLON.Vector3.Zero();
  48247. }
  48248. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48249. // In case the direction is present.
  48250. if (this.direction) {
  48251. if (!this.transformedDirection) {
  48252. this.transformedDirection = BABYLON.Vector3.Zero();
  48253. }
  48254. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48255. }
  48256. return true;
  48257. }
  48258. return false;
  48259. };
  48260. /**
  48261. * Return the depth scale used for the shadow map.
  48262. * @returns the depth scale.
  48263. */
  48264. ShadowLight.prototype.getDepthScale = function () {
  48265. return 50.0;
  48266. };
  48267. /**
  48268. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48269. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48270. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48271. */
  48272. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48273. return this.transformedDirection ? this.transformedDirection : this.direction;
  48274. };
  48275. /**
  48276. * Returns the ShadowLight absolute position in the World.
  48277. * @returns the position vector in world space
  48278. */
  48279. ShadowLight.prototype.getAbsolutePosition = function () {
  48280. return this.transformedPosition ? this.transformedPosition : this.position;
  48281. };
  48282. /**
  48283. * Sets the ShadowLight direction toward the passed target.
  48284. * @param target The point tot target in local space
  48285. * @returns the updated ShadowLight direction
  48286. */
  48287. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48288. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48289. return this.direction;
  48290. };
  48291. /**
  48292. * Returns the light rotation in euler definition.
  48293. * @returns the x y z rotation in local space.
  48294. */
  48295. ShadowLight.prototype.getRotation = function () {
  48296. this.direction.normalize();
  48297. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48298. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48299. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48300. };
  48301. /**
  48302. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48303. * @returns true if a cube texture needs to be use
  48304. */
  48305. ShadowLight.prototype.needCube = function () {
  48306. return false;
  48307. };
  48308. /**
  48309. * Detects if the projection matrix requires to be recomputed this frame.
  48310. * @returns true if it requires to be recomputed otherwise, false.
  48311. */
  48312. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48313. return this._needProjectionMatrixCompute;
  48314. };
  48315. /**
  48316. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48317. */
  48318. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48319. this._needProjectionMatrixCompute = true;
  48320. };
  48321. /**
  48322. * Get the world matrix of the sahdow lights.
  48323. * @hidden Internal Use Only
  48324. */
  48325. ShadowLight.prototype._getWorldMatrix = function () {
  48326. if (!this._worldMatrix) {
  48327. this._worldMatrix = BABYLON.Matrix.Identity();
  48328. }
  48329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48330. return this._worldMatrix;
  48331. };
  48332. /**
  48333. * Gets the minZ used for shadow according to both the scene and the light.
  48334. * @param activeCamera The camera we are returning the min for
  48335. * @returns the depth min z
  48336. */
  48337. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48338. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48339. };
  48340. /**
  48341. * Gets the maxZ used for shadow according to both the scene and the light.
  48342. * @param activeCamera The camera we are returning the max for
  48343. * @returns the depth max z
  48344. */
  48345. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48346. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48347. };
  48348. /**
  48349. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48350. * @param matrix The materix to updated with the projection information
  48351. * @param viewMatrix The transform matrix of the light
  48352. * @param renderList The list of mesh to render in the map
  48353. * @returns The current light
  48354. */
  48355. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48356. if (this.customProjectionMatrixBuilder) {
  48357. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48358. }
  48359. else {
  48360. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48361. }
  48362. return this;
  48363. };
  48364. __decorate([
  48365. BABYLON.serializeAsVector3()
  48366. ], ShadowLight.prototype, "position", null);
  48367. __decorate([
  48368. BABYLON.serializeAsVector3()
  48369. ], ShadowLight.prototype, "direction", null);
  48370. __decorate([
  48371. BABYLON.serialize()
  48372. ], ShadowLight.prototype, "shadowMinZ", null);
  48373. __decorate([
  48374. BABYLON.serialize()
  48375. ], ShadowLight.prototype, "shadowMaxZ", null);
  48376. return ShadowLight;
  48377. }(BABYLON.Light));
  48378. BABYLON.ShadowLight = ShadowLight;
  48379. })(BABYLON || (BABYLON = {}));
  48380. //# sourceMappingURL=babylon.shadowLight.js.map
  48381. var BABYLON;
  48382. (function (BABYLON) {
  48383. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  48384. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  48385. });
  48386. /**
  48387. * A point light is a light defined by an unique point in world space.
  48388. * The light is emitted in every direction from this point.
  48389. * A good example of a point light is a standard light bulb.
  48390. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48391. */
  48392. var PointLight = /** @class */ (function (_super) {
  48393. __extends(PointLight, _super);
  48394. /**
  48395. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48396. * A PointLight emits the light in every direction.
  48397. * It can cast shadows.
  48398. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48399. * ```javascript
  48400. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48401. * ```
  48402. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48403. * @param name The light friendly name
  48404. * @param position The position of the point light in the scene
  48405. * @param scene The scene the lights belongs to
  48406. */
  48407. function PointLight(name, position, scene) {
  48408. var _this = _super.call(this, name, scene) || this;
  48409. _this._shadowAngle = Math.PI / 2;
  48410. _this.position = position;
  48411. return _this;
  48412. }
  48413. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48414. /**
  48415. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48416. * This specifies what angle the shadow will use to be created.
  48417. *
  48418. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48419. */
  48420. get: function () {
  48421. return this._shadowAngle;
  48422. },
  48423. /**
  48424. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48425. * This specifies what angle the shadow will use to be created.
  48426. *
  48427. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48428. */
  48429. set: function (value) {
  48430. this._shadowAngle = value;
  48431. this.forceProjectionMatrixCompute();
  48432. },
  48433. enumerable: true,
  48434. configurable: true
  48435. });
  48436. Object.defineProperty(PointLight.prototype, "direction", {
  48437. /**
  48438. * Gets the direction if it has been set.
  48439. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48440. */
  48441. get: function () {
  48442. return this._direction;
  48443. },
  48444. /**
  48445. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48446. */
  48447. set: function (value) {
  48448. var previousNeedCube = this.needCube();
  48449. this._direction = value;
  48450. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48451. this._shadowGenerator.recreateShadowMap();
  48452. }
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. /**
  48458. * Returns the string "PointLight"
  48459. * @returns the class name
  48460. */
  48461. PointLight.prototype.getClassName = function () {
  48462. return "PointLight";
  48463. };
  48464. /**
  48465. * Returns the integer 0.
  48466. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48467. */
  48468. PointLight.prototype.getTypeID = function () {
  48469. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48470. };
  48471. /**
  48472. * Specifies wether or not the shadowmap should be a cube texture.
  48473. * @returns true if the shadowmap needs to be a cube texture.
  48474. */
  48475. PointLight.prototype.needCube = function () {
  48476. return !this.direction;
  48477. };
  48478. /**
  48479. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48480. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48481. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48482. */
  48483. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48484. if (this.direction) {
  48485. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48486. }
  48487. else {
  48488. switch (faceIndex) {
  48489. case 0:
  48490. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48491. case 1:
  48492. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48493. case 2:
  48494. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48495. case 3:
  48496. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48497. case 4:
  48498. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48499. case 5:
  48500. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48501. }
  48502. }
  48503. return BABYLON.Vector3.Zero();
  48504. };
  48505. /**
  48506. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48507. * - fov = PI / 2
  48508. * - aspect ratio : 1.0
  48509. * - z-near and far equal to the active camera minZ and maxZ.
  48510. * Returns the PointLight.
  48511. */
  48512. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48513. var activeCamera = this.getScene().activeCamera;
  48514. if (!activeCamera) {
  48515. return;
  48516. }
  48517. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48518. };
  48519. PointLight.prototype._buildUniformLayout = function () {
  48520. this._uniformBuffer.addUniform("vLightData", 4);
  48521. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48522. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48523. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48524. this._uniformBuffer.addUniform("depthValues", 2);
  48525. this._uniformBuffer.create();
  48526. };
  48527. /**
  48528. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48529. * @param effect The effect to update
  48530. * @param lightIndex The index of the light in the effect to update
  48531. * @returns The point light
  48532. */
  48533. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48534. if (this.computeTransformedInformation()) {
  48535. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48536. return this;
  48537. }
  48538. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48539. return this;
  48540. };
  48541. /**
  48542. * Prepares the list of defines specific to the light type.
  48543. * @param defines the list of defines
  48544. * @param lightIndex defines the index of the light for the effect
  48545. */
  48546. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48547. defines["POINTLIGHT" + lightIndex] = true;
  48548. };
  48549. __decorate([
  48550. BABYLON.serialize()
  48551. ], PointLight.prototype, "shadowAngle", null);
  48552. return PointLight;
  48553. }(BABYLON.ShadowLight));
  48554. BABYLON.PointLight = PointLight;
  48555. })(BABYLON || (BABYLON = {}));
  48556. //# sourceMappingURL=babylon.pointLight.js.map
  48557. var BABYLON;
  48558. (function (BABYLON) {
  48559. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  48560. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  48561. });
  48562. /**
  48563. * A directional light is defined by a direction (what a surprise!).
  48564. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48565. * 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.
  48566. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48567. */
  48568. var DirectionalLight = /** @class */ (function (_super) {
  48569. __extends(DirectionalLight, _super);
  48570. /**
  48571. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48572. * The directional light is emitted from everywhere in the given direction.
  48573. * It can cast shawdows.
  48574. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48575. * @param name The friendly name of the light
  48576. * @param direction The direction of the light
  48577. * @param scene The scene the light belongs to
  48578. */
  48579. function DirectionalLight(name, direction, scene) {
  48580. var _this = _super.call(this, name, scene) || this;
  48581. _this._shadowFrustumSize = 0;
  48582. _this._shadowOrthoScale = 0.1;
  48583. /**
  48584. * Automatically compute the projection matrix to best fit (including all the casters)
  48585. * on each frame.
  48586. */
  48587. _this.autoUpdateExtends = true;
  48588. // Cache
  48589. _this._orthoLeft = Number.MAX_VALUE;
  48590. _this._orthoRight = Number.MIN_VALUE;
  48591. _this._orthoTop = Number.MIN_VALUE;
  48592. _this._orthoBottom = Number.MAX_VALUE;
  48593. _this.position = direction.scale(-1.0);
  48594. _this.direction = direction;
  48595. return _this;
  48596. }
  48597. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48598. /**
  48599. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48600. */
  48601. get: function () {
  48602. return this._shadowFrustumSize;
  48603. },
  48604. /**
  48605. * Specifies a fix frustum size for the shadow generation.
  48606. */
  48607. set: function (value) {
  48608. this._shadowFrustumSize = value;
  48609. this.forceProjectionMatrixCompute();
  48610. },
  48611. enumerable: true,
  48612. configurable: true
  48613. });
  48614. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48615. /**
  48616. * Gets the shadow projection scale against the optimal computed one.
  48617. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48618. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48619. */
  48620. get: function () {
  48621. return this._shadowOrthoScale;
  48622. },
  48623. /**
  48624. * Sets the shadow projection scale against the optimal computed one.
  48625. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48626. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48627. */
  48628. set: function (value) {
  48629. this._shadowOrthoScale = value;
  48630. this.forceProjectionMatrixCompute();
  48631. },
  48632. enumerable: true,
  48633. configurable: true
  48634. });
  48635. /**
  48636. * Returns the string "DirectionalLight".
  48637. * @return The class name
  48638. */
  48639. DirectionalLight.prototype.getClassName = function () {
  48640. return "DirectionalLight";
  48641. };
  48642. /**
  48643. * Returns the integer 1.
  48644. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48645. */
  48646. DirectionalLight.prototype.getTypeID = function () {
  48647. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48648. };
  48649. /**
  48650. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48651. * Returns the DirectionalLight Shadow projection matrix.
  48652. */
  48653. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48654. if (this.shadowFrustumSize > 0) {
  48655. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48656. }
  48657. else {
  48658. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48659. }
  48660. };
  48661. /**
  48662. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48663. * Returns the DirectionalLight Shadow projection matrix.
  48664. */
  48665. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48666. var activeCamera = this.getScene().activeCamera;
  48667. if (!activeCamera) {
  48668. return;
  48669. }
  48670. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48671. };
  48672. /**
  48673. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48674. * Returns the DirectionalLight Shadow projection matrix.
  48675. */
  48676. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48677. var activeCamera = this.getScene().activeCamera;
  48678. if (!activeCamera) {
  48679. return;
  48680. }
  48681. // Check extends
  48682. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48683. var tempVector3 = BABYLON.Vector3.Zero();
  48684. this._orthoLeft = Number.MAX_VALUE;
  48685. this._orthoRight = Number.MIN_VALUE;
  48686. this._orthoTop = Number.MIN_VALUE;
  48687. this._orthoBottom = Number.MAX_VALUE;
  48688. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48689. var mesh = renderList[meshIndex];
  48690. if (!mesh) {
  48691. continue;
  48692. }
  48693. var boundingInfo = mesh.getBoundingInfo();
  48694. var boundingBox = boundingInfo.boundingBox;
  48695. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48696. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48697. if (tempVector3.x < this._orthoLeft)
  48698. this._orthoLeft = tempVector3.x;
  48699. if (tempVector3.y < this._orthoBottom)
  48700. this._orthoBottom = tempVector3.y;
  48701. if (tempVector3.x > this._orthoRight)
  48702. this._orthoRight = tempVector3.x;
  48703. if (tempVector3.y > this._orthoTop)
  48704. this._orthoTop = tempVector3.y;
  48705. }
  48706. }
  48707. }
  48708. var xOffset = this._orthoRight - this._orthoLeft;
  48709. var yOffset = this._orthoTop - this._orthoBottom;
  48710. 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);
  48711. };
  48712. DirectionalLight.prototype._buildUniformLayout = function () {
  48713. this._uniformBuffer.addUniform("vLightData", 4);
  48714. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48715. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48716. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48717. this._uniformBuffer.addUniform("depthValues", 2);
  48718. this._uniformBuffer.create();
  48719. };
  48720. /**
  48721. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48722. * @param effect The effect to update
  48723. * @param lightIndex The index of the light in the effect to update
  48724. * @returns The directional light
  48725. */
  48726. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48727. if (this.computeTransformedInformation()) {
  48728. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48729. return this;
  48730. }
  48731. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48732. return this;
  48733. };
  48734. /**
  48735. * Gets the minZ used for shadow according to both the scene and the light.
  48736. *
  48737. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48738. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48739. * @param activeCamera The camera we are returning the min for
  48740. * @returns the depth min z
  48741. */
  48742. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48743. return 1;
  48744. };
  48745. /**
  48746. * Gets the maxZ used for shadow according to both the scene and the light.
  48747. *
  48748. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48749. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48750. * @param activeCamera The camera we are returning the max for
  48751. * @returns the depth max z
  48752. */
  48753. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48754. return 1;
  48755. };
  48756. /**
  48757. * Prepares the list of defines specific to the light type.
  48758. * @param defines the list of defines
  48759. * @param lightIndex defines the index of the light for the effect
  48760. */
  48761. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48762. defines["DIRLIGHT" + lightIndex] = true;
  48763. };
  48764. __decorate([
  48765. BABYLON.serialize()
  48766. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48767. __decorate([
  48768. BABYLON.serialize()
  48769. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48770. __decorate([
  48771. BABYLON.serialize()
  48772. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48773. return DirectionalLight;
  48774. }(BABYLON.ShadowLight));
  48775. BABYLON.DirectionalLight = DirectionalLight;
  48776. })(BABYLON || (BABYLON = {}));
  48777. //# sourceMappingURL=babylon.directionalLight.js.map
  48778. var BABYLON;
  48779. (function (BABYLON) {
  48780. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  48781. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  48782. });
  48783. /**
  48784. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48785. * These values define a cone of light starting from the position, emitting toward the direction.
  48786. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48787. * and the exponent defines the speed of the decay of the light with distance (reach).
  48788. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48789. */
  48790. var SpotLight = /** @class */ (function (_super) {
  48791. __extends(SpotLight, _super);
  48792. /**
  48793. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48794. * It can cast shadows.
  48795. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48796. * @param name The light friendly name
  48797. * @param position The position of the spot light in the scene
  48798. * @param direction The direction of the light in the scene
  48799. * @param angle The cone angle of the light in Radians
  48800. * @param exponent The light decay speed with the distance from the emission spot
  48801. * @param scene The scene the lights belongs to
  48802. */
  48803. function SpotLight(name, position, direction, angle, exponent, scene) {
  48804. var _this = _super.call(this, name, scene) || this;
  48805. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48806. _this._projectionTextureLightNear = 1e-6;
  48807. _this._projectionTextureLightFar = 1000.0;
  48808. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48809. _this._projectionTextureViewLightDirty = true;
  48810. _this._projectionTextureProjectionLightDirty = true;
  48811. _this._projectionTextureDirty = true;
  48812. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48813. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48814. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48815. _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);
  48816. _this.position = position;
  48817. _this.direction = direction;
  48818. _this.angle = angle;
  48819. _this.exponent = exponent;
  48820. return _this;
  48821. }
  48822. Object.defineProperty(SpotLight.prototype, "angle", {
  48823. /**
  48824. * Gets the cone angle of the spot light in Radians.
  48825. */
  48826. get: function () {
  48827. return this._angle;
  48828. },
  48829. /**
  48830. * Sets the cone angle of the spot light in Radians.
  48831. */
  48832. set: function (value) {
  48833. this._angle = value;
  48834. this._projectionTextureProjectionLightDirty = true;
  48835. this.forceProjectionMatrixCompute();
  48836. },
  48837. enumerable: true,
  48838. configurable: true
  48839. });
  48840. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48841. /**
  48842. * Allows scaling the angle of the light for shadow generation only.
  48843. */
  48844. get: function () {
  48845. return this._shadowAngleScale;
  48846. },
  48847. /**
  48848. * Allows scaling the angle of the light for shadow generation only.
  48849. */
  48850. set: function (value) {
  48851. this._shadowAngleScale = value;
  48852. this.forceProjectionMatrixCompute();
  48853. },
  48854. enumerable: true,
  48855. configurable: true
  48856. });
  48857. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48858. /**
  48859. * Allows reading the projecton texture
  48860. */
  48861. get: function () {
  48862. return this._projectionTextureMatrix;
  48863. },
  48864. enumerable: true,
  48865. configurable: true
  48866. });
  48867. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48868. /**
  48869. * Gets the near clip of the Spotlight for texture projection.
  48870. */
  48871. get: function () {
  48872. return this._projectionTextureLightNear;
  48873. },
  48874. /**
  48875. * Sets the near clip of the Spotlight for texture projection.
  48876. */
  48877. set: function (value) {
  48878. this._projectionTextureLightNear = value;
  48879. this._projectionTextureProjectionLightDirty = true;
  48880. },
  48881. enumerable: true,
  48882. configurable: true
  48883. });
  48884. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48885. /**
  48886. * Gets the far clip of the Spotlight for texture projection.
  48887. */
  48888. get: function () {
  48889. return this._projectionTextureLightFar;
  48890. },
  48891. /**
  48892. * Sets the far clip of the Spotlight for texture projection.
  48893. */
  48894. set: function (value) {
  48895. this._projectionTextureLightFar = value;
  48896. this._projectionTextureProjectionLightDirty = true;
  48897. },
  48898. enumerable: true,
  48899. configurable: true
  48900. });
  48901. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  48902. /**
  48903. * Gets the Up vector of the Spotlight for texture projection.
  48904. */
  48905. get: function () {
  48906. return this._projectionTextureUpDirection;
  48907. },
  48908. /**
  48909. * Sets the Up vector of the Spotlight for texture projection.
  48910. */
  48911. set: function (value) {
  48912. this._projectionTextureUpDirection = value;
  48913. this._projectionTextureProjectionLightDirty = true;
  48914. },
  48915. enumerable: true,
  48916. configurable: true
  48917. });
  48918. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  48919. /**
  48920. * Gets the projection texture of the light.
  48921. */
  48922. get: function () {
  48923. return this._projectionTexture;
  48924. },
  48925. /**
  48926. * Sets the projection texture of the light.
  48927. */
  48928. set: function (value) {
  48929. this._projectionTexture = value;
  48930. this._projectionTextureDirty = true;
  48931. },
  48932. enumerable: true,
  48933. configurable: true
  48934. });
  48935. /**
  48936. * Returns the string "SpotLight".
  48937. * @returns the class name
  48938. */
  48939. SpotLight.prototype.getClassName = function () {
  48940. return "SpotLight";
  48941. };
  48942. /**
  48943. * Returns the integer 2.
  48944. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48945. */
  48946. SpotLight.prototype.getTypeID = function () {
  48947. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  48948. };
  48949. /**
  48950. * Overrides the direction setter to recompute the projection texture view light Matrix.
  48951. */
  48952. SpotLight.prototype._setDirection = function (value) {
  48953. _super.prototype._setDirection.call(this, value);
  48954. this._projectionTextureViewLightDirty = true;
  48955. };
  48956. /**
  48957. * Overrides the position setter to recompute the projection texture view light Matrix.
  48958. */
  48959. SpotLight.prototype._setPosition = function (value) {
  48960. _super.prototype._setPosition.call(this, value);
  48961. this._projectionTextureViewLightDirty = true;
  48962. };
  48963. /**
  48964. * 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.
  48965. * Returns the SpotLight.
  48966. */
  48967. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48968. var activeCamera = this.getScene().activeCamera;
  48969. if (!activeCamera) {
  48970. return;
  48971. }
  48972. this._shadowAngleScale = this._shadowAngleScale || 1;
  48973. var angle = this._shadowAngleScale * this._angle;
  48974. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48975. };
  48976. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  48977. this._projectionTextureViewLightDirty = false;
  48978. this._projectionTextureDirty = true;
  48979. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  48980. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  48981. };
  48982. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  48983. this._projectionTextureProjectionLightDirty = false;
  48984. this._projectionTextureDirty = true;
  48985. var light_far = this.projectionTextureLightFar;
  48986. var light_near = this.projectionTextureLightNear;
  48987. var P = light_far / (light_far - light_near);
  48988. var Q = -P * light_near;
  48989. var S = 1.0 / Math.tan(this._angle / 2.0);
  48990. var A = 1.0;
  48991. 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);
  48992. };
  48993. /**
  48994. * Main function for light texture projection matrix computing.
  48995. */
  48996. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  48997. this._projectionTextureDirty = false;
  48998. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  48999. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49000. };
  49001. SpotLight.prototype._buildUniformLayout = function () {
  49002. this._uniformBuffer.addUniform("vLightData", 4);
  49003. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49004. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49005. this._uniformBuffer.addUniform("vLightDirection", 3);
  49006. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49007. this._uniformBuffer.addUniform("depthValues", 2);
  49008. this._uniformBuffer.create();
  49009. };
  49010. /**
  49011. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49012. * @param effect The effect to update
  49013. * @param lightIndex The index of the light in the effect to update
  49014. * @returns The spot light
  49015. */
  49016. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49017. var normalizeDirection;
  49018. if (this.computeTransformedInformation()) {
  49019. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49020. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49021. }
  49022. else {
  49023. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49024. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49025. }
  49026. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49027. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49028. if (this._projectionTextureViewLightDirty) {
  49029. this._computeProjectionTextureViewLightMatrix();
  49030. }
  49031. if (this._projectionTextureProjectionLightDirty) {
  49032. this._computeProjectionTextureProjectionLightMatrix();
  49033. }
  49034. if (this._projectionTextureDirty) {
  49035. this._computeProjectionTextureMatrix();
  49036. }
  49037. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49038. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49039. }
  49040. return this;
  49041. };
  49042. /**
  49043. * Disposes the light and the associated resources.
  49044. */
  49045. SpotLight.prototype.dispose = function () {
  49046. _super.prototype.dispose.call(this);
  49047. if (this._projectionTexture) {
  49048. this._projectionTexture.dispose();
  49049. }
  49050. };
  49051. /**
  49052. * Prepares the list of defines specific to the light type.
  49053. * @param defines the list of defines
  49054. * @param lightIndex defines the index of the light for the effect
  49055. */
  49056. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49057. defines["SPOTLIGHT" + lightIndex] = true;
  49058. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49059. };
  49060. __decorate([
  49061. BABYLON.serialize()
  49062. ], SpotLight.prototype, "angle", null);
  49063. __decorate([
  49064. BABYLON.serialize()
  49065. ], SpotLight.prototype, "shadowAngleScale", null);
  49066. __decorate([
  49067. BABYLON.serialize()
  49068. ], SpotLight.prototype, "exponent", void 0);
  49069. __decorate([
  49070. BABYLON.serialize()
  49071. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49072. __decorate([
  49073. BABYLON.serialize()
  49074. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49075. __decorate([
  49076. BABYLON.serialize()
  49077. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49078. __decorate([
  49079. BABYLON.serializeAsTexture("projectedLightTexture")
  49080. ], SpotLight.prototype, "_projectionTexture", void 0);
  49081. return SpotLight;
  49082. }(BABYLON.ShadowLight));
  49083. BABYLON.SpotLight = SpotLight;
  49084. })(BABYLON || (BABYLON = {}));
  49085. //# sourceMappingURL=babylon.spotLight.js.map
  49086. var BABYLON;
  49087. (function (BABYLON) {
  49088. /**
  49089. * Class used to override all child animations of a given target
  49090. */
  49091. var AnimationPropertiesOverride = /** @class */ (function () {
  49092. function AnimationPropertiesOverride() {
  49093. /**
  49094. * Gets or sets a value indicating if animation blending must be used
  49095. */
  49096. this.enableBlending = false;
  49097. /**
  49098. * Gets or sets the blending speed to use when enableBlending is true
  49099. */
  49100. this.blendingSpeed = 0.01;
  49101. /**
  49102. * Gets or sets the default loop mode to use
  49103. */
  49104. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49105. }
  49106. return AnimationPropertiesOverride;
  49107. }());
  49108. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49109. })(BABYLON || (BABYLON = {}));
  49110. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49111. var BABYLON;
  49112. (function (BABYLON) {
  49113. /**
  49114. * Represents the range of an animation
  49115. */
  49116. var AnimationRange = /** @class */ (function () {
  49117. /**
  49118. * Initializes the range of an animation
  49119. * @param name The name of the animation range
  49120. * @param from The starting frame of the animation
  49121. * @param to The ending frame of the animation
  49122. */
  49123. function AnimationRange(
  49124. /**The name of the animation range**/
  49125. name,
  49126. /**The starting frame of the animation */
  49127. from,
  49128. /**The ending frame of the animation*/
  49129. to) {
  49130. this.name = name;
  49131. this.from = from;
  49132. this.to = to;
  49133. }
  49134. /**
  49135. * Makes a copy of the animation range
  49136. * @returns A copy of the animation range
  49137. */
  49138. AnimationRange.prototype.clone = function () {
  49139. return new AnimationRange(this.name, this.from, this.to);
  49140. };
  49141. return AnimationRange;
  49142. }());
  49143. BABYLON.AnimationRange = AnimationRange;
  49144. /**
  49145. * Composed of a frame, and an action function
  49146. */
  49147. var AnimationEvent = /** @class */ (function () {
  49148. /**
  49149. * Initializes the animation event
  49150. * @param frame The frame for which the event is triggered
  49151. * @param action The event to perform when triggered
  49152. * @param onlyOnce Specifies if the event should be triggered only once
  49153. */
  49154. function AnimationEvent(
  49155. /** The frame for which the event is triggered **/
  49156. frame,
  49157. /** The event to perform when triggered **/
  49158. action,
  49159. /** Specifies if the event should be triggered only once**/
  49160. onlyOnce) {
  49161. this.frame = frame;
  49162. this.action = action;
  49163. this.onlyOnce = onlyOnce;
  49164. /**
  49165. * Specifies if the animation event is done
  49166. */
  49167. this.isDone = false;
  49168. }
  49169. /** @hidden */
  49170. AnimationEvent.prototype._clone = function () {
  49171. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49172. };
  49173. return AnimationEvent;
  49174. }());
  49175. BABYLON.AnimationEvent = AnimationEvent;
  49176. /**
  49177. * A cursor which tracks a point on a path
  49178. */
  49179. var PathCursor = /** @class */ (function () {
  49180. /**
  49181. * Initializes the path cursor
  49182. * @param path The path to track
  49183. */
  49184. function PathCursor(path) {
  49185. this.path = path;
  49186. /**
  49187. * Stores path cursor callbacks for when an onchange event is triggered
  49188. */
  49189. this._onchange = new Array();
  49190. /**
  49191. * The value of the path cursor
  49192. */
  49193. this.value = 0;
  49194. /**
  49195. * The animation array of the path cursor
  49196. */
  49197. this.animations = new Array();
  49198. }
  49199. /**
  49200. * Gets the cursor point on the path
  49201. * @returns A point on the path cursor at the cursor location
  49202. */
  49203. PathCursor.prototype.getPoint = function () {
  49204. var point = this.path.getPointAtLengthPosition(this.value);
  49205. return new BABYLON.Vector3(point.x, 0, point.y);
  49206. };
  49207. /**
  49208. * Moves the cursor ahead by the step amount
  49209. * @param step The amount to move the cursor forward
  49210. * @returns This path cursor
  49211. */
  49212. PathCursor.prototype.moveAhead = function (step) {
  49213. if (step === void 0) { step = 0.002; }
  49214. this.move(step);
  49215. return this;
  49216. };
  49217. /**
  49218. * Moves the cursor behind by the step amount
  49219. * @param step The amount to move the cursor back
  49220. * @returns This path cursor
  49221. */
  49222. PathCursor.prototype.moveBack = function (step) {
  49223. if (step === void 0) { step = 0.002; }
  49224. this.move(-step);
  49225. return this;
  49226. };
  49227. /**
  49228. * Moves the cursor by the step amount
  49229. * If the step amount is greater than one, an exception is thrown
  49230. * @param step The amount to move the cursor
  49231. * @returns This path cursor
  49232. */
  49233. PathCursor.prototype.move = function (step) {
  49234. if (Math.abs(step) > 1) {
  49235. throw "step size should be less than 1.";
  49236. }
  49237. this.value += step;
  49238. this.ensureLimits();
  49239. this.raiseOnChange();
  49240. return this;
  49241. };
  49242. /**
  49243. * Ensures that the value is limited between zero and one
  49244. * @returns This path cursor
  49245. */
  49246. PathCursor.prototype.ensureLimits = function () {
  49247. while (this.value > 1) {
  49248. this.value -= 1;
  49249. }
  49250. while (this.value < 0) {
  49251. this.value += 1;
  49252. }
  49253. return this;
  49254. };
  49255. /**
  49256. * Runs onchange callbacks on change (used by the animation engine)
  49257. * @returns This path cursor
  49258. */
  49259. PathCursor.prototype.raiseOnChange = function () {
  49260. var _this = this;
  49261. this._onchange.forEach(function (f) { return f(_this); });
  49262. return this;
  49263. };
  49264. /**
  49265. * Executes a function on change
  49266. * @param f A path cursor onchange callback
  49267. * @returns This path cursor
  49268. */
  49269. PathCursor.prototype.onchange = function (f) {
  49270. this._onchange.push(f);
  49271. return this;
  49272. };
  49273. return PathCursor;
  49274. }());
  49275. BABYLON.PathCursor = PathCursor;
  49276. /**
  49277. * Enum for the animation key frame interpolation type
  49278. */
  49279. var AnimationKeyInterpolation;
  49280. (function (AnimationKeyInterpolation) {
  49281. /**
  49282. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49283. */
  49284. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49285. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49286. /**
  49287. * Class used to store any kind of animation
  49288. */
  49289. var Animation = /** @class */ (function () {
  49290. /**
  49291. * Initializes the animation
  49292. * @param name Name of the animation
  49293. * @param targetProperty Property to animate
  49294. * @param framePerSecond The frames per second of the animation
  49295. * @param dataType The data type of the animation
  49296. * @param loopMode The loop mode of the animation
  49297. * @param enableBlendings Specifies if blending should be enabled
  49298. */
  49299. function Animation(
  49300. /**Name of the animation */
  49301. name,
  49302. /**Property to animate */
  49303. targetProperty,
  49304. /**The frames per second of the animation */
  49305. framePerSecond,
  49306. /**The data type of the animation */
  49307. dataType,
  49308. /**The loop mode of the animation */
  49309. loopMode,
  49310. /**Specifies if blending should be enabled */
  49311. enableBlending) {
  49312. this.name = name;
  49313. this.targetProperty = targetProperty;
  49314. this.framePerSecond = framePerSecond;
  49315. this.dataType = dataType;
  49316. this.loopMode = loopMode;
  49317. this.enableBlending = enableBlending;
  49318. /**
  49319. * @hidden Internal use only
  49320. */
  49321. this._runtimeAnimations = new Array();
  49322. /**
  49323. * The set of event that will be linked to this animation
  49324. */
  49325. this._events = new Array();
  49326. /**
  49327. * Stores the blending speed of the animation
  49328. */
  49329. this.blendingSpeed = 0.01;
  49330. /**
  49331. * Stores the animation ranges for the animation
  49332. */
  49333. this._ranges = {};
  49334. this.targetPropertyPath = targetProperty.split(".");
  49335. this.dataType = dataType;
  49336. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49337. }
  49338. /**
  49339. * @hidden Internal use
  49340. */
  49341. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49342. var dataType = undefined;
  49343. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49344. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49345. }
  49346. else if (from instanceof BABYLON.Quaternion) {
  49347. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49348. }
  49349. else if (from instanceof BABYLON.Vector3) {
  49350. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49351. }
  49352. else if (from instanceof BABYLON.Vector2) {
  49353. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49354. }
  49355. else if (from instanceof BABYLON.Color3) {
  49356. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49357. }
  49358. else if (from instanceof BABYLON.Size) {
  49359. dataType = Animation.ANIMATIONTYPE_SIZE;
  49360. }
  49361. if (dataType == undefined) {
  49362. return null;
  49363. }
  49364. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49365. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49366. animation.setKeys(keys);
  49367. if (easingFunction !== undefined) {
  49368. animation.setEasingFunction(easingFunction);
  49369. }
  49370. return animation;
  49371. };
  49372. /**
  49373. * Sets up an animation
  49374. * @param property The property to animate
  49375. * @param animationType The animation type to apply
  49376. * @param framePerSecond The frames per second of the animation
  49377. * @param easingFunction The easing function used in the animation
  49378. * @returns The created animation
  49379. */
  49380. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49381. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49382. animation.setEasingFunction(easingFunction);
  49383. return animation;
  49384. };
  49385. /**
  49386. * Create and start an animation on a node
  49387. * @param name defines the name of the global animation that will be run on all nodes
  49388. * @param node defines the root node where the animation will take place
  49389. * @param targetProperty defines property to animate
  49390. * @param framePerSecond defines the number of frame per second yo use
  49391. * @param totalFrame defines the number of frames in total
  49392. * @param from defines the initial value
  49393. * @param to defines the final value
  49394. * @param loopMode defines which loop mode you want to use (off by default)
  49395. * @param easingFunction defines the easing function to use (linear by default)
  49396. * @param onAnimationEnd defines the callback to call when animation end
  49397. * @returns the animatable created for this animation
  49398. */
  49399. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49400. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49401. if (!animation) {
  49402. return null;
  49403. }
  49404. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49405. };
  49406. /**
  49407. * Create and start an animation on a node and its descendants
  49408. * @param name defines the name of the global animation that will be run on all nodes
  49409. * @param node defines the root node where the animation will take place
  49410. * @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
  49411. * @param targetProperty defines property to animate
  49412. * @param framePerSecond defines the number of frame per second to use
  49413. * @param totalFrame defines the number of frames in total
  49414. * @param from defines the initial value
  49415. * @param to defines the final value
  49416. * @param loopMode defines which loop mode you want to use (off by default)
  49417. * @param easingFunction defines the easing function to use (linear by default)
  49418. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49419. * @returns the list of animatables created for all nodes
  49420. * @example https://www.babylonjs-playground.com/#MH0VLI
  49421. */
  49422. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49423. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49424. if (!animation) {
  49425. return null;
  49426. }
  49427. var scene = node.getScene();
  49428. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49429. };
  49430. /**
  49431. * Creates a new animation, merges it with the existing animations and starts it
  49432. * @param name Name of the animation
  49433. * @param node Node which contains the scene that begins the animations
  49434. * @param targetProperty Specifies which property to animate
  49435. * @param framePerSecond The frames per second of the animation
  49436. * @param totalFrame The total number of frames
  49437. * @param from The frame at the beginning of the animation
  49438. * @param to The frame at the end of the animation
  49439. * @param loopMode Specifies the loop mode of the animation
  49440. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49441. * @param onAnimationEnd Callback to run once the animation is complete
  49442. * @returns Nullable animation
  49443. */
  49444. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49445. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49446. if (!animation) {
  49447. return null;
  49448. }
  49449. node.animations.push(animation);
  49450. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49451. };
  49452. /**
  49453. * Transition property of an host to the target Value
  49454. * @param property The property to transition
  49455. * @param targetValue The target Value of the property
  49456. * @param host The object where the property to animate belongs
  49457. * @param scene Scene used to run the animation
  49458. * @param frameRate Framerate (in frame/s) to use
  49459. * @param transition The transition type we want to use
  49460. * @param duration The duration of the animation, in milliseconds
  49461. * @param onAnimationEnd Callback trigger at the end of the animation
  49462. * @returns Nullable animation
  49463. */
  49464. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49465. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49466. if (duration <= 0) {
  49467. host[property] = targetValue;
  49468. if (onAnimationEnd) {
  49469. onAnimationEnd();
  49470. }
  49471. return null;
  49472. }
  49473. var endFrame = frameRate * (duration / 1000);
  49474. transition.setKeys([{
  49475. frame: 0,
  49476. value: host[property].clone ? host[property].clone() : host[property]
  49477. },
  49478. {
  49479. frame: endFrame,
  49480. value: targetValue
  49481. }]);
  49482. if (!host.animations) {
  49483. host.animations = [];
  49484. }
  49485. host.animations.push(transition);
  49486. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49487. animation.onAnimationEnd = onAnimationEnd;
  49488. return animation;
  49489. };
  49490. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49491. /**
  49492. * Return the array of runtime animations currently using this animation
  49493. */
  49494. get: function () {
  49495. return this._runtimeAnimations;
  49496. },
  49497. enumerable: true,
  49498. configurable: true
  49499. });
  49500. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49501. /**
  49502. * Specifies if any of the runtime animations are currently running
  49503. */
  49504. get: function () {
  49505. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49506. var runtimeAnimation = _a[_i];
  49507. if (!runtimeAnimation.isStopped) {
  49508. return true;
  49509. }
  49510. }
  49511. return false;
  49512. },
  49513. enumerable: true,
  49514. configurable: true
  49515. });
  49516. // Methods
  49517. /**
  49518. * Converts the animation to a string
  49519. * @param fullDetails support for multiple levels of logging within scene loading
  49520. * @returns String form of the animation
  49521. */
  49522. Animation.prototype.toString = function (fullDetails) {
  49523. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49524. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49525. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49526. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49527. if (fullDetails) {
  49528. ret += ", Ranges: {";
  49529. var first = true;
  49530. for (var name in this._ranges) {
  49531. if (first) {
  49532. ret += ", ";
  49533. first = false;
  49534. }
  49535. ret += name;
  49536. }
  49537. ret += "}";
  49538. }
  49539. return ret;
  49540. };
  49541. /**
  49542. * Add an event to this animation
  49543. * @param event Event to add
  49544. */
  49545. Animation.prototype.addEvent = function (event) {
  49546. this._events.push(event);
  49547. };
  49548. /**
  49549. * Remove all events found at the given frame
  49550. * @param frame The frame to remove events from
  49551. */
  49552. Animation.prototype.removeEvents = function (frame) {
  49553. for (var index = 0; index < this._events.length; index++) {
  49554. if (this._events[index].frame === frame) {
  49555. this._events.splice(index, 1);
  49556. index--;
  49557. }
  49558. }
  49559. };
  49560. /**
  49561. * Retrieves all the events from the animation
  49562. * @returns Events from the animation
  49563. */
  49564. Animation.prototype.getEvents = function () {
  49565. return this._events;
  49566. };
  49567. /**
  49568. * Creates an animation range
  49569. * @param name Name of the animation range
  49570. * @param from Starting frame of the animation range
  49571. * @param to Ending frame of the animation
  49572. */
  49573. Animation.prototype.createRange = function (name, from, to) {
  49574. // check name not already in use; could happen for bones after serialized
  49575. if (!this._ranges[name]) {
  49576. this._ranges[name] = new AnimationRange(name, from, to);
  49577. }
  49578. };
  49579. /**
  49580. * Deletes an animation range by name
  49581. * @param name Name of the animation range to delete
  49582. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49583. */
  49584. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49585. if (deleteFrames === void 0) { deleteFrames = true; }
  49586. var range = this._ranges[name];
  49587. if (!range) {
  49588. return;
  49589. }
  49590. if (deleteFrames) {
  49591. var from = range.from;
  49592. var to = range.to;
  49593. // this loop MUST go high to low for multiple splices to work
  49594. for (var key = this._keys.length - 1; key >= 0; key--) {
  49595. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49596. this._keys.splice(key, 1);
  49597. }
  49598. }
  49599. }
  49600. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49601. };
  49602. /**
  49603. * Gets the animation range by name, or null if not defined
  49604. * @param name Name of the animation range
  49605. * @returns Nullable animation range
  49606. */
  49607. Animation.prototype.getRange = function (name) {
  49608. return this._ranges[name];
  49609. };
  49610. /**
  49611. * Gets the key frames from the animation
  49612. * @returns The key frames of the animation
  49613. */
  49614. Animation.prototype.getKeys = function () {
  49615. return this._keys;
  49616. };
  49617. /**
  49618. * Gets the highest frame rate of the animation
  49619. * @returns Highest frame rate of the animation
  49620. */
  49621. Animation.prototype.getHighestFrame = function () {
  49622. var ret = 0;
  49623. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49624. if (ret < this._keys[key].frame) {
  49625. ret = this._keys[key].frame;
  49626. }
  49627. }
  49628. return ret;
  49629. };
  49630. /**
  49631. * Gets the easing function of the animation
  49632. * @returns Easing function of the animation
  49633. */
  49634. Animation.prototype.getEasingFunction = function () {
  49635. return this._easingFunction;
  49636. };
  49637. /**
  49638. * Sets the easing function of the animation
  49639. * @param easingFunction A custom mathematical formula for animation
  49640. */
  49641. Animation.prototype.setEasingFunction = function (easingFunction) {
  49642. this._easingFunction = easingFunction;
  49643. };
  49644. /**
  49645. * Interpolates a scalar linearly
  49646. * @param startValue Start value of the animation curve
  49647. * @param endValue End value of the animation curve
  49648. * @param gradient Scalar amount to interpolate
  49649. * @returns Interpolated scalar value
  49650. */
  49651. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49652. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49653. };
  49654. /**
  49655. * Interpolates a scalar cubically
  49656. * @param startValue Start value of the animation curve
  49657. * @param outTangent End tangent of the animation
  49658. * @param endValue End value of the animation curve
  49659. * @param inTangent Start tangent of the animation curve
  49660. * @param gradient Scalar amount to interpolate
  49661. * @returns Interpolated scalar value
  49662. */
  49663. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49664. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49665. };
  49666. /**
  49667. * Interpolates a quaternion using a spherical linear interpolation
  49668. * @param startValue Start value of the animation curve
  49669. * @param endValue End value of the animation curve
  49670. * @param gradient Scalar amount to interpolate
  49671. * @returns Interpolated quaternion value
  49672. */
  49673. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49674. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49675. };
  49676. /**
  49677. * Interpolates a quaternion cubically
  49678. * @param startValue Start value of the animation curve
  49679. * @param outTangent End tangent of the animation curve
  49680. * @param endValue End value of the animation curve
  49681. * @param inTangent Start tangent of the animation curve
  49682. * @param gradient Scalar amount to interpolate
  49683. * @returns Interpolated quaternion value
  49684. */
  49685. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49686. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49687. };
  49688. /**
  49689. * Interpolates a Vector3 linearl
  49690. * @param startValue Start value of the animation curve
  49691. * @param endValue End value of the animation curve
  49692. * @param gradient Scalar amount to interpolate
  49693. * @returns Interpolated scalar value
  49694. */
  49695. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49696. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49697. };
  49698. /**
  49699. * Interpolates a Vector3 cubically
  49700. * @param startValue Start value of the animation curve
  49701. * @param outTangent End tangent of the animation
  49702. * @param endValue End value of the animation curve
  49703. * @param inTangent Start tangent of the animation curve
  49704. * @param gradient Scalar amount to interpolate
  49705. * @returns InterpolatedVector3 value
  49706. */
  49707. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49708. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49709. };
  49710. /**
  49711. * Interpolates a Vector2 linearly
  49712. * @param startValue Start value of the animation curve
  49713. * @param endValue End value of the animation curve
  49714. * @param gradient Scalar amount to interpolate
  49715. * @returns Interpolated Vector2 value
  49716. */
  49717. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49718. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49719. };
  49720. /**
  49721. * Interpolates a Vector2 cubically
  49722. * @param startValue Start value of the animation curve
  49723. * @param outTangent End tangent of the animation
  49724. * @param endValue End value of the animation curve
  49725. * @param inTangent Start tangent of the animation curve
  49726. * @param gradient Scalar amount to interpolate
  49727. * @returns Interpolated Vector2 value
  49728. */
  49729. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49730. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49731. };
  49732. /**
  49733. * Interpolates a size linearly
  49734. * @param startValue Start value of the animation curve
  49735. * @param endValue End value of the animation curve
  49736. * @param gradient Scalar amount to interpolate
  49737. * @returns Interpolated Size value
  49738. */
  49739. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49740. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49741. };
  49742. /**
  49743. * Interpolates a Color3 linearly
  49744. * @param startValue Start value of the animation curve
  49745. * @param endValue End value of the animation curve
  49746. * @param gradient Scalar amount to interpolate
  49747. * @returns Interpolated Color3 value
  49748. */
  49749. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49750. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49751. };
  49752. /**
  49753. * @hidden Internal use only
  49754. */
  49755. Animation.prototype._getKeyValue = function (value) {
  49756. if (typeof value === "function") {
  49757. return value();
  49758. }
  49759. return value;
  49760. };
  49761. /**
  49762. * @hidden Internal use only
  49763. */
  49764. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49765. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49766. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49767. }
  49768. var keys = this.getKeys();
  49769. // Try to get a hash to find the right key
  49770. 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));
  49771. if (keys[startKeyIndex].frame >= currentFrame) {
  49772. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49773. startKeyIndex--;
  49774. }
  49775. }
  49776. for (var key = startKeyIndex; key < keys.length; key++) {
  49777. var endKey = keys[key + 1];
  49778. if (endKey.frame >= currentFrame) {
  49779. var startKey = keys[key];
  49780. var startValue = this._getKeyValue(startKey.value);
  49781. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49782. return startValue;
  49783. }
  49784. var endValue = this._getKeyValue(endKey.value);
  49785. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49786. var frameDelta = endKey.frame - startKey.frame;
  49787. // gradient : percent of currentFrame between the frame inf and the frame sup
  49788. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49789. // check for easingFunction and correction of gradient
  49790. var easingFunction = this.getEasingFunction();
  49791. if (easingFunction != null) {
  49792. gradient = easingFunction.ease(gradient);
  49793. }
  49794. switch (this.dataType) {
  49795. // Float
  49796. case Animation.ANIMATIONTYPE_FLOAT:
  49797. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49798. switch (loopMode) {
  49799. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49800. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49801. return floatValue;
  49802. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49803. return offsetValue * repeatCount + floatValue;
  49804. }
  49805. break;
  49806. // Quaternion
  49807. case Animation.ANIMATIONTYPE_QUATERNION:
  49808. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49809. switch (loopMode) {
  49810. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49811. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49812. return quatValue;
  49813. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49814. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49815. }
  49816. return quatValue;
  49817. // Vector3
  49818. case Animation.ANIMATIONTYPE_VECTOR3:
  49819. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49820. switch (loopMode) {
  49821. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49822. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49823. return vec3Value;
  49824. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49825. return vec3Value.add(offsetValue.scale(repeatCount));
  49826. }
  49827. // Vector2
  49828. case Animation.ANIMATIONTYPE_VECTOR2:
  49829. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49830. switch (loopMode) {
  49831. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49832. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49833. return vec2Value;
  49834. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49835. return vec2Value.add(offsetValue.scale(repeatCount));
  49836. }
  49837. // Size
  49838. case Animation.ANIMATIONTYPE_SIZE:
  49839. switch (loopMode) {
  49840. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49841. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49842. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49843. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49844. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49845. }
  49846. // Color3
  49847. case Animation.ANIMATIONTYPE_COLOR3:
  49848. switch (loopMode) {
  49849. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49850. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49851. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49852. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49853. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49854. }
  49855. // Matrix
  49856. case Animation.ANIMATIONTYPE_MATRIX:
  49857. switch (loopMode) {
  49858. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49859. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49860. if (Animation.AllowMatricesInterpolation) {
  49861. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49862. }
  49863. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49864. return startValue;
  49865. }
  49866. default:
  49867. break;
  49868. }
  49869. break;
  49870. }
  49871. }
  49872. return this._getKeyValue(keys[keys.length - 1].value);
  49873. };
  49874. /**
  49875. * Defines the function to use to interpolate matrices
  49876. * @param startValue defines the start matrix
  49877. * @param endValue defines the end matrix
  49878. * @param gradient defines the gradient between both matrices
  49879. * @param result defines an optional target matrix where to store the interpolation
  49880. * @returns the interpolated matrix
  49881. */
  49882. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49883. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49884. if (result) {
  49885. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49886. return result;
  49887. }
  49888. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49889. }
  49890. if (result) {
  49891. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49892. return result;
  49893. }
  49894. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49895. };
  49896. /**
  49897. * Makes a copy of the animation
  49898. * @returns Cloned animation
  49899. */
  49900. Animation.prototype.clone = function () {
  49901. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49902. clone.enableBlending = this.enableBlending;
  49903. clone.blendingSpeed = this.blendingSpeed;
  49904. if (this._keys) {
  49905. clone.setKeys(this._keys);
  49906. }
  49907. if (this._ranges) {
  49908. clone._ranges = {};
  49909. for (var name in this._ranges) {
  49910. var range = this._ranges[name];
  49911. if (!range) {
  49912. continue;
  49913. }
  49914. clone._ranges[name] = range.clone();
  49915. }
  49916. }
  49917. return clone;
  49918. };
  49919. /**
  49920. * Sets the key frames of the animation
  49921. * @param values The animation key frames to set
  49922. */
  49923. Animation.prototype.setKeys = function (values) {
  49924. this._keys = values.slice(0);
  49925. };
  49926. /**
  49927. * Serializes the animation to an object
  49928. * @returns Serialized object
  49929. */
  49930. Animation.prototype.serialize = function () {
  49931. var serializationObject = {};
  49932. serializationObject.name = this.name;
  49933. serializationObject.property = this.targetProperty;
  49934. serializationObject.framePerSecond = this.framePerSecond;
  49935. serializationObject.dataType = this.dataType;
  49936. serializationObject.loopBehavior = this.loopMode;
  49937. serializationObject.enableBlending = this.enableBlending;
  49938. serializationObject.blendingSpeed = this.blendingSpeed;
  49939. var dataType = this.dataType;
  49940. serializationObject.keys = [];
  49941. var keys = this.getKeys();
  49942. for (var index = 0; index < keys.length; index++) {
  49943. var animationKey = keys[index];
  49944. var key = {};
  49945. key.frame = animationKey.frame;
  49946. switch (dataType) {
  49947. case Animation.ANIMATIONTYPE_FLOAT:
  49948. key.values = [animationKey.value];
  49949. break;
  49950. case Animation.ANIMATIONTYPE_QUATERNION:
  49951. case Animation.ANIMATIONTYPE_MATRIX:
  49952. case Animation.ANIMATIONTYPE_VECTOR3:
  49953. case Animation.ANIMATIONTYPE_COLOR3:
  49954. key.values = animationKey.value.asArray();
  49955. break;
  49956. }
  49957. serializationObject.keys.push(key);
  49958. }
  49959. serializationObject.ranges = [];
  49960. for (var name in this._ranges) {
  49961. var source = this._ranges[name];
  49962. if (!source) {
  49963. continue;
  49964. }
  49965. var range = {};
  49966. range.name = name;
  49967. range.from = source.from;
  49968. range.to = source.to;
  49969. serializationObject.ranges.push(range);
  49970. }
  49971. return serializationObject;
  49972. };
  49973. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  49974. /**
  49975. * Get the float animation type
  49976. */
  49977. get: function () {
  49978. return Animation._ANIMATIONTYPE_FLOAT;
  49979. },
  49980. enumerable: true,
  49981. configurable: true
  49982. });
  49983. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  49984. /**
  49985. * Get the Vector3 animation type
  49986. */
  49987. get: function () {
  49988. return Animation._ANIMATIONTYPE_VECTOR3;
  49989. },
  49990. enumerable: true,
  49991. configurable: true
  49992. });
  49993. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  49994. /**
  49995. * Get the Vectpr2 animation type
  49996. */
  49997. get: function () {
  49998. return Animation._ANIMATIONTYPE_VECTOR2;
  49999. },
  50000. enumerable: true,
  50001. configurable: true
  50002. });
  50003. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50004. /**
  50005. * Get the Size animation type
  50006. */
  50007. get: function () {
  50008. return Animation._ANIMATIONTYPE_SIZE;
  50009. },
  50010. enumerable: true,
  50011. configurable: true
  50012. });
  50013. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50014. /**
  50015. * Get the Quaternion animation type
  50016. */
  50017. get: function () {
  50018. return Animation._ANIMATIONTYPE_QUATERNION;
  50019. },
  50020. enumerable: true,
  50021. configurable: true
  50022. });
  50023. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50024. /**
  50025. * Get the Matrix animation type
  50026. */
  50027. get: function () {
  50028. return Animation._ANIMATIONTYPE_MATRIX;
  50029. },
  50030. enumerable: true,
  50031. configurable: true
  50032. });
  50033. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50034. /**
  50035. * Get the Color3 animation type
  50036. */
  50037. get: function () {
  50038. return Animation._ANIMATIONTYPE_COLOR3;
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50044. /**
  50045. * Get the Relative Loop Mode
  50046. */
  50047. get: function () {
  50048. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50049. },
  50050. enumerable: true,
  50051. configurable: true
  50052. });
  50053. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50054. /**
  50055. * Get the Cycle Loop Mode
  50056. */
  50057. get: function () {
  50058. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50064. /**
  50065. * Get the Constant Loop Mode
  50066. */
  50067. get: function () {
  50068. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50069. },
  50070. enumerable: true,
  50071. configurable: true
  50072. });
  50073. /** @hidden */
  50074. Animation._UniversalLerp = function (left, right, amount) {
  50075. var constructor = left.constructor;
  50076. if (constructor.Lerp) { // Lerp supported
  50077. return constructor.Lerp(left, right, amount);
  50078. }
  50079. else if (constructor.Slerp) { // Slerp supported
  50080. return constructor.Slerp(left, right, amount);
  50081. }
  50082. else if (left.toFixed) { // Number
  50083. return left * (1.0 - amount) + amount * right;
  50084. }
  50085. else { // Blending not supported
  50086. return right;
  50087. }
  50088. };
  50089. /**
  50090. * Parses an animation object and creates an animation
  50091. * @param parsedAnimation Parsed animation object
  50092. * @returns Animation object
  50093. */
  50094. Animation.Parse = function (parsedAnimation) {
  50095. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50096. var dataType = parsedAnimation.dataType;
  50097. var keys = [];
  50098. var data;
  50099. var index;
  50100. if (parsedAnimation.enableBlending) {
  50101. animation.enableBlending = parsedAnimation.enableBlending;
  50102. }
  50103. if (parsedAnimation.blendingSpeed) {
  50104. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50105. }
  50106. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50107. var key = parsedAnimation.keys[index];
  50108. var inTangent;
  50109. var outTangent;
  50110. switch (dataType) {
  50111. case Animation.ANIMATIONTYPE_FLOAT:
  50112. data = key.values[0];
  50113. if (key.values.length >= 1) {
  50114. inTangent = key.values[1];
  50115. }
  50116. if (key.values.length >= 2) {
  50117. outTangent = key.values[2];
  50118. }
  50119. break;
  50120. case Animation.ANIMATIONTYPE_QUATERNION:
  50121. data = BABYLON.Quaternion.FromArray(key.values);
  50122. if (key.values.length >= 8) {
  50123. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50124. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50125. inTangent = _inTangent;
  50126. }
  50127. }
  50128. if (key.values.length >= 12) {
  50129. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50130. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50131. outTangent = _outTangent;
  50132. }
  50133. }
  50134. break;
  50135. case Animation.ANIMATIONTYPE_MATRIX:
  50136. data = BABYLON.Matrix.FromArray(key.values);
  50137. break;
  50138. case Animation.ANIMATIONTYPE_COLOR3:
  50139. data = BABYLON.Color3.FromArray(key.values);
  50140. break;
  50141. case Animation.ANIMATIONTYPE_VECTOR3:
  50142. default:
  50143. data = BABYLON.Vector3.FromArray(key.values);
  50144. break;
  50145. }
  50146. var keyData = {};
  50147. keyData.frame = key.frame;
  50148. keyData.value = data;
  50149. if (inTangent != undefined) {
  50150. keyData.inTangent = inTangent;
  50151. }
  50152. if (outTangent != undefined) {
  50153. keyData.outTangent = outTangent;
  50154. }
  50155. keys.push(keyData);
  50156. }
  50157. animation.setKeys(keys);
  50158. if (parsedAnimation.ranges) {
  50159. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50160. data = parsedAnimation.ranges[index];
  50161. animation.createRange(data.name, data.from, data.to);
  50162. }
  50163. }
  50164. return animation;
  50165. };
  50166. /**
  50167. * Appends the serialized animations from the source animations
  50168. * @param source Source containing the animations
  50169. * @param destination Target to store the animations
  50170. */
  50171. Animation.AppendSerializedAnimations = function (source, destination) {
  50172. if (source.animations) {
  50173. destination.animations = [];
  50174. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50175. var animation = source.animations[animationIndex];
  50176. destination.animations.push(animation.serialize());
  50177. }
  50178. }
  50179. };
  50180. /**
  50181. * Use matrix interpolation instead of using direct key value when animating matrices
  50182. */
  50183. Animation.AllowMatricesInterpolation = false;
  50184. /**
  50185. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50186. */
  50187. Animation.AllowMatrixDecomposeForInterpolation = true;
  50188. // Statics
  50189. /**
  50190. * Float animation type
  50191. */
  50192. Animation._ANIMATIONTYPE_FLOAT = 0;
  50193. /**
  50194. * Vector3 animation type
  50195. */
  50196. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50197. /**
  50198. * Quaternion animation type
  50199. */
  50200. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50201. /**
  50202. * Matrix animation type
  50203. */
  50204. Animation._ANIMATIONTYPE_MATRIX = 3;
  50205. /**
  50206. * Color3 animation type
  50207. */
  50208. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50209. /**
  50210. * Vector2 animation type
  50211. */
  50212. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50213. /**
  50214. * Size animation type
  50215. */
  50216. Animation._ANIMATIONTYPE_SIZE = 6;
  50217. /**
  50218. * Relative Loop Mode
  50219. */
  50220. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50221. /**
  50222. * Cycle Loop Mode
  50223. */
  50224. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50225. /**
  50226. * Constant Loop Mode
  50227. */
  50228. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50229. return Animation;
  50230. }());
  50231. BABYLON.Animation = Animation;
  50232. })(BABYLON || (BABYLON = {}));
  50233. //# sourceMappingURL=babylon.animation.js.map
  50234. var BABYLON;
  50235. (function (BABYLON) {
  50236. /**
  50237. * This class defines the direct association between an animation and a target
  50238. */
  50239. var TargetedAnimation = /** @class */ (function () {
  50240. function TargetedAnimation() {
  50241. }
  50242. return TargetedAnimation;
  50243. }());
  50244. BABYLON.TargetedAnimation = TargetedAnimation;
  50245. /**
  50246. * Use this class to create coordinated animations on multiple targets
  50247. */
  50248. var AnimationGroup = /** @class */ (function () {
  50249. function AnimationGroup(name, scene) {
  50250. if (scene === void 0) { scene = null; }
  50251. this.name = name;
  50252. this._targetedAnimations = new Array();
  50253. this._animatables = new Array();
  50254. this._from = Number.MAX_VALUE;
  50255. this._to = -Number.MAX_VALUE;
  50256. this._speedRatio = 1;
  50257. this.onAnimationEndObservable = new BABYLON.Observable();
  50258. /**
  50259. * This observable will notify when all animations have ended.
  50260. */
  50261. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50262. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50263. this._scene.animationGroups.push(this);
  50264. }
  50265. Object.defineProperty(AnimationGroup.prototype, "from", {
  50266. /**
  50267. * Gets the first frame
  50268. */
  50269. get: function () {
  50270. return this._from;
  50271. },
  50272. enumerable: true,
  50273. configurable: true
  50274. });
  50275. Object.defineProperty(AnimationGroup.prototype, "to", {
  50276. /**
  50277. * Gets the last frame
  50278. */
  50279. get: function () {
  50280. return this._to;
  50281. },
  50282. enumerable: true,
  50283. configurable: true
  50284. });
  50285. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50286. /**
  50287. * Define if the animations are started
  50288. */
  50289. get: function () {
  50290. return this._isStarted;
  50291. },
  50292. enumerable: true,
  50293. configurable: true
  50294. });
  50295. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50296. /**
  50297. * Gets or sets the speed ratio to use for all animations
  50298. */
  50299. get: function () {
  50300. return this._speedRatio;
  50301. },
  50302. /**
  50303. * Gets or sets the speed ratio to use for all animations
  50304. */
  50305. set: function (value) {
  50306. if (this._speedRatio === value) {
  50307. return;
  50308. }
  50309. this._speedRatio = value;
  50310. for (var index = 0; index < this._animatables.length; index++) {
  50311. var animatable = this._animatables[index];
  50312. animatable.speedRatio = this._speedRatio;
  50313. }
  50314. },
  50315. enumerable: true,
  50316. configurable: true
  50317. });
  50318. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50319. /**
  50320. * Gets the targeted animations for this animation group
  50321. */
  50322. get: function () {
  50323. return this._targetedAnimations;
  50324. },
  50325. enumerable: true,
  50326. configurable: true
  50327. });
  50328. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50329. /**
  50330. * returning the list of animatables controlled by this animation group.
  50331. */
  50332. get: function () {
  50333. return this._animatables;
  50334. },
  50335. enumerable: true,
  50336. configurable: true
  50337. });
  50338. /**
  50339. * Add an animation (with its target) in the group
  50340. * @param animation defines the animation we want to add
  50341. * @param target defines the target of the animation
  50342. * @returns the {BABYLON.TargetedAnimation} object
  50343. */
  50344. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50345. var targetedAnimation = {
  50346. animation: animation,
  50347. target: target
  50348. };
  50349. var keys = animation.getKeys();
  50350. if (this._from > keys[0].frame) {
  50351. this._from = keys[0].frame;
  50352. }
  50353. if (this._to < keys[keys.length - 1].frame) {
  50354. this._to = keys[keys.length - 1].frame;
  50355. }
  50356. this._targetedAnimations.push(targetedAnimation);
  50357. return targetedAnimation;
  50358. };
  50359. /**
  50360. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50361. * It can add constant keys at begin or end
  50362. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50363. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50364. */
  50365. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50366. if (beginFrame === void 0) { beginFrame = null; }
  50367. if (endFrame === void 0) { endFrame = null; }
  50368. if (beginFrame == null)
  50369. beginFrame = this._from;
  50370. if (endFrame == null)
  50371. endFrame = this._to;
  50372. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50373. var targetedAnimation = this._targetedAnimations[index];
  50374. var keys = targetedAnimation.animation.getKeys();
  50375. var startKey = keys[0];
  50376. var endKey = keys[keys.length - 1];
  50377. if (startKey.frame > beginFrame) {
  50378. var newKey = {
  50379. frame: beginFrame,
  50380. value: startKey.value,
  50381. inTangent: startKey.inTangent,
  50382. outTangent: startKey.outTangent,
  50383. interpolation: startKey.interpolation
  50384. };
  50385. keys.splice(0, 0, newKey);
  50386. }
  50387. if (endKey.frame < endFrame) {
  50388. var newKey = {
  50389. frame: endFrame,
  50390. value: endKey.value,
  50391. inTangent: endKey.outTangent,
  50392. outTangent: endKey.outTangent,
  50393. interpolation: endKey.interpolation
  50394. };
  50395. keys.push(newKey);
  50396. }
  50397. }
  50398. this._from = beginFrame;
  50399. this._to = endFrame;
  50400. return this;
  50401. };
  50402. /**
  50403. * Start all animations on given targets
  50404. * @param loop defines if animations must loop
  50405. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50406. * @param from defines the from key (optional)
  50407. * @param to defines the to key (optional)
  50408. * @returns the current animation group
  50409. */
  50410. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50411. var _this = this;
  50412. if (loop === void 0) { loop = false; }
  50413. if (speedRatio === void 0) { speedRatio = 1; }
  50414. if (this._isStarted || this._targetedAnimations.length === 0) {
  50415. return this;
  50416. }
  50417. var _loop_1 = function (targetedAnimation) {
  50418. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50419. animatable.onAnimationEnd = function () {
  50420. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50421. _this._checkAnimationGroupEnded(animatable);
  50422. };
  50423. this_1._animatables.push(animatable);
  50424. };
  50425. var this_1 = this;
  50426. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50427. var targetedAnimation = _a[_i];
  50428. _loop_1(targetedAnimation);
  50429. }
  50430. this._speedRatio = speedRatio;
  50431. this._isStarted = true;
  50432. return this;
  50433. };
  50434. /**
  50435. * Pause all animations
  50436. */
  50437. AnimationGroup.prototype.pause = function () {
  50438. if (!this._isStarted) {
  50439. return this;
  50440. }
  50441. for (var index = 0; index < this._animatables.length; index++) {
  50442. var animatable = this._animatables[index];
  50443. animatable.pause();
  50444. }
  50445. return this;
  50446. };
  50447. /**
  50448. * Play all animations to initial state
  50449. * This function will start() the animations if they were not started or will restart() them if they were paused
  50450. * @param loop defines if animations must loop
  50451. */
  50452. AnimationGroup.prototype.play = function (loop) {
  50453. // only if all animatables are ready and exist
  50454. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50455. if (loop !== undefined) {
  50456. for (var index = 0; index < this._animatables.length; index++) {
  50457. var animatable = this._animatables[index];
  50458. animatable.loopAnimation = loop;
  50459. }
  50460. }
  50461. this.restart();
  50462. }
  50463. else {
  50464. this.stop();
  50465. this.start(loop, this._speedRatio);
  50466. }
  50467. return this;
  50468. };
  50469. /**
  50470. * Reset all animations to initial state
  50471. */
  50472. AnimationGroup.prototype.reset = function () {
  50473. if (!this._isStarted) {
  50474. return this;
  50475. }
  50476. for (var index = 0; index < this._animatables.length; index++) {
  50477. var animatable = this._animatables[index];
  50478. animatable.reset();
  50479. }
  50480. return this;
  50481. };
  50482. /**
  50483. * Restart animations from key 0
  50484. */
  50485. AnimationGroup.prototype.restart = function () {
  50486. if (!this._isStarted) {
  50487. return this;
  50488. }
  50489. for (var index = 0; index < this._animatables.length; index++) {
  50490. var animatable = this._animatables[index];
  50491. animatable.restart();
  50492. }
  50493. return this;
  50494. };
  50495. /**
  50496. * Stop all animations
  50497. */
  50498. AnimationGroup.prototype.stop = function () {
  50499. if (!this._isStarted) {
  50500. return this;
  50501. }
  50502. var list = this._animatables.slice();
  50503. for (var index = 0; index < list.length; index++) {
  50504. list[index].stop();
  50505. }
  50506. this._isStarted = false;
  50507. return this;
  50508. };
  50509. /**
  50510. * Set animation weight for all animatables
  50511. * @param weight defines the weight to use
  50512. * @return the animationGroup
  50513. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50514. */
  50515. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50516. for (var index = 0; index < this._animatables.length; index++) {
  50517. var animatable = this._animatables[index];
  50518. animatable.weight = weight;
  50519. }
  50520. return this;
  50521. };
  50522. /**
  50523. * Synchronize and normalize all animatables with a source animatable
  50524. * @param root defines the root animatable to synchronize with
  50525. * @return the animationGroup
  50526. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50527. */
  50528. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50529. for (var index = 0; index < this._animatables.length; index++) {
  50530. var animatable = this._animatables[index];
  50531. animatable.syncWith(root);
  50532. }
  50533. return this;
  50534. };
  50535. /**
  50536. * Goes to a specific frame in this animation group
  50537. * @param frame the frame number to go to
  50538. * @return the animationGroup
  50539. */
  50540. AnimationGroup.prototype.goToFrame = function (frame) {
  50541. if (!this._isStarted) {
  50542. return this;
  50543. }
  50544. for (var index = 0; index < this._animatables.length; index++) {
  50545. var animatable = this._animatables[index];
  50546. animatable.goToFrame(frame);
  50547. }
  50548. return this;
  50549. };
  50550. /**
  50551. * Dispose all associated resources
  50552. */
  50553. AnimationGroup.prototype.dispose = function () {
  50554. this._targetedAnimations = [];
  50555. this._animatables = [];
  50556. var index = this._scene.animationGroups.indexOf(this);
  50557. if (index > -1) {
  50558. this._scene.animationGroups.splice(index, 1);
  50559. }
  50560. };
  50561. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50562. // animatable should be taken out of the array
  50563. var idx = this._animatables.indexOf(animatable);
  50564. if (idx > -1) {
  50565. this._animatables.splice(idx, 1);
  50566. }
  50567. // all animatables were removed? animation group ended!
  50568. if (this._animatables.length === 0) {
  50569. this._isStarted = false;
  50570. this.onAnimationGroupEndObservable.notifyObservers(this);
  50571. }
  50572. };
  50573. return AnimationGroup;
  50574. }());
  50575. BABYLON.AnimationGroup = AnimationGroup;
  50576. })(BABYLON || (BABYLON = {}));
  50577. //# sourceMappingURL=babylon.animationGroup.js.map
  50578. var BABYLON;
  50579. (function (BABYLON) {
  50580. /**
  50581. * Defines a runtime animation
  50582. */
  50583. var RuntimeAnimation = /** @class */ (function () {
  50584. /**
  50585. * Create a new RuntimeAnimation object
  50586. * @param target defines the target of the animation
  50587. * @param animation defines the source animation object
  50588. * @param scene defines the hosting scene
  50589. * @param host defines the initiating Animatable
  50590. */
  50591. function RuntimeAnimation(target, animation, scene, host) {
  50592. var _this = this;
  50593. this._events = new Array();
  50594. /**
  50595. * The current frame of the runtime animation
  50596. */
  50597. this._currentFrame = 0;
  50598. /**
  50599. * The original value of the runtime animation
  50600. */
  50601. this._originalValue = new Array();
  50602. /**
  50603. * The offsets cache of the runtime animation
  50604. */
  50605. this._offsetsCache = {};
  50606. /**
  50607. * The high limits cache of the runtime animation
  50608. */
  50609. this._highLimitsCache = {};
  50610. /**
  50611. * Specifies if the runtime animation has been stopped
  50612. */
  50613. this._stopped = false;
  50614. /**
  50615. * The blending factor of the runtime animation
  50616. */
  50617. this._blendingFactor = 0;
  50618. /**
  50619. * The target path of the runtime animation
  50620. */
  50621. this._targetPath = "";
  50622. /**
  50623. * The weight of the runtime animation
  50624. */
  50625. this._weight = 1.0;
  50626. /**
  50627. * The ratio offset of the runtime animation
  50628. */
  50629. this._ratioOffset = 0;
  50630. /**
  50631. * The previous delay of the runtime animation
  50632. */
  50633. this._previousDelay = 0;
  50634. /**
  50635. * The previous ratio of the runtime animation
  50636. */
  50637. this._previousRatio = 0;
  50638. this._animation = animation;
  50639. this._target = target;
  50640. this._scene = scene;
  50641. this._host = host;
  50642. animation._runtimeAnimations.push(this);
  50643. // Cloning events locally
  50644. var events = animation.getEvents();
  50645. if (events && events.length > 0) {
  50646. events.forEach(function (e) {
  50647. _this._events.push(e._clone());
  50648. });
  50649. }
  50650. }
  50651. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50652. /**
  50653. * Gets the current frame of the runtime animation
  50654. */
  50655. get: function () {
  50656. return this._currentFrame;
  50657. },
  50658. enumerable: true,
  50659. configurable: true
  50660. });
  50661. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50662. /**
  50663. * Gets the weight of the runtime animation
  50664. */
  50665. get: function () {
  50666. return this._weight;
  50667. },
  50668. enumerable: true,
  50669. configurable: true
  50670. });
  50671. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50672. /**
  50673. * Gets the current value of the runtime animation
  50674. */
  50675. get: function () {
  50676. return this._currentValue;
  50677. },
  50678. enumerable: true,
  50679. configurable: true
  50680. });
  50681. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50682. /**
  50683. * Gets the target path of the runtime animation
  50684. */
  50685. get: function () {
  50686. return this._targetPath;
  50687. },
  50688. enumerable: true,
  50689. configurable: true
  50690. });
  50691. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50692. /**
  50693. * Gets the actual target of the runtime animation
  50694. */
  50695. get: function () {
  50696. return this._activeTarget;
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50702. /**
  50703. * Gets the animation from the runtime animation
  50704. */
  50705. get: function () {
  50706. return this._animation;
  50707. },
  50708. enumerable: true,
  50709. configurable: true
  50710. });
  50711. /**
  50712. * Resets the runtime animation to the beginning
  50713. * @param restoreOriginal defines whether to restore the target property to the original value
  50714. */
  50715. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50716. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50717. if (restoreOriginal) {
  50718. if (this._target instanceof Array) {
  50719. var index = 0;
  50720. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50721. var target = _a[_i];
  50722. if (this._originalValue[index] !== undefined) {
  50723. this._setValue(target, this._originalValue[index], -1);
  50724. }
  50725. index++;
  50726. }
  50727. }
  50728. else {
  50729. if (this._originalValue[0] !== undefined) {
  50730. this._setValue(this._target, this._originalValue[0], -1);
  50731. }
  50732. }
  50733. }
  50734. this._offsetsCache = {};
  50735. this._highLimitsCache = {};
  50736. this._currentFrame = 0;
  50737. this._blendingFactor = 0;
  50738. this._originalValue = new Array();
  50739. // Events
  50740. for (var index = 0; index < this._events.length; index++) {
  50741. this._events[index].isDone = false;
  50742. }
  50743. };
  50744. /**
  50745. * Specifies if the runtime animation is stopped
  50746. * @returns Boolean specifying if the runtime animation is stopped
  50747. */
  50748. RuntimeAnimation.prototype.isStopped = function () {
  50749. return this._stopped;
  50750. };
  50751. /**
  50752. * Disposes of the runtime animation
  50753. */
  50754. RuntimeAnimation.prototype.dispose = function () {
  50755. var index = this._animation.runtimeAnimations.indexOf(this);
  50756. if (index > -1) {
  50757. this._animation.runtimeAnimations.splice(index, 1);
  50758. }
  50759. };
  50760. /**
  50761. * Interpolates the animation from the current frame
  50762. * @param currentFrame The frame to interpolate the animation to
  50763. * @param repeatCount The number of times that the animation should loop
  50764. * @param loopMode The type of looping mode to use
  50765. * @param offsetValue Animation offset value
  50766. * @param highLimitValue The high limit value
  50767. * @returns The interpolated value
  50768. */
  50769. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50770. this._currentFrame = currentFrame;
  50771. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50772. this._workValue = BABYLON.Matrix.Zero();
  50773. }
  50774. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50775. };
  50776. /**
  50777. * Apply the interpolated value to the target
  50778. * @param currentValue defines the value computed by the animation
  50779. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50780. */
  50781. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50782. if (weight === void 0) { weight = 1.0; }
  50783. if (this._target instanceof Array) {
  50784. var index = 0;
  50785. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50786. var target = _a[_i];
  50787. this._setValue(target, currentValue, weight, index);
  50788. index++;
  50789. }
  50790. }
  50791. else {
  50792. this._setValue(this._target, currentValue, weight);
  50793. }
  50794. };
  50795. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50796. if (targetIndex === void 0) { targetIndex = 0; }
  50797. // Set value
  50798. var path;
  50799. var destination;
  50800. var targetPropertyPath = this._animation.targetPropertyPath;
  50801. if (targetPropertyPath.length > 1) {
  50802. var property = target[targetPropertyPath[0]];
  50803. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50804. property = property[targetPropertyPath[index]];
  50805. }
  50806. path = targetPropertyPath[targetPropertyPath.length - 1];
  50807. destination = property;
  50808. }
  50809. else {
  50810. path = targetPropertyPath[0];
  50811. destination = target;
  50812. }
  50813. this._targetPath = path;
  50814. this._activeTarget = destination;
  50815. this._weight = weight;
  50816. if (this._originalValue[targetIndex] === undefined) {
  50817. var originalValue = void 0;
  50818. if (destination.getRestPose && path === "_matrix") { // For bones
  50819. originalValue = destination.getRestPose();
  50820. }
  50821. else {
  50822. originalValue = destination[path];
  50823. }
  50824. if (originalValue && originalValue.clone) {
  50825. this._originalValue[targetIndex] = originalValue.clone();
  50826. }
  50827. else {
  50828. this._originalValue[targetIndex] = originalValue;
  50829. }
  50830. }
  50831. // Blending
  50832. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50833. if (enableBlending && this._blendingFactor <= 1.0) {
  50834. if (!this._originalBlendValue) {
  50835. var originalValue = destination[path];
  50836. if (originalValue.clone) {
  50837. this._originalBlendValue = originalValue.clone();
  50838. }
  50839. else {
  50840. this._originalBlendValue = originalValue;
  50841. }
  50842. }
  50843. if (this._originalBlendValue.m) { // Matrix
  50844. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50845. if (this._currentValue) {
  50846. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50847. }
  50848. else {
  50849. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50850. }
  50851. }
  50852. else {
  50853. if (this._currentValue) {
  50854. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50855. }
  50856. else {
  50857. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50858. }
  50859. }
  50860. }
  50861. else {
  50862. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50863. }
  50864. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50865. this._blendingFactor += blendingSpeed;
  50866. }
  50867. else {
  50868. this._currentValue = currentValue;
  50869. }
  50870. if (weight !== -1.0) {
  50871. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50872. }
  50873. else {
  50874. destination[path] = this._currentValue;
  50875. }
  50876. if (target.markAsDirty) {
  50877. target.markAsDirty(this._animation.targetProperty);
  50878. }
  50879. };
  50880. /**
  50881. * Gets the loop pmode of the runtime animation
  50882. * @returns Loop Mode
  50883. */
  50884. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50885. if (this._target && this._target.animationPropertiesOverride) {
  50886. return this._target.animationPropertiesOverride.loopMode;
  50887. }
  50888. return this._animation.loopMode;
  50889. };
  50890. /**
  50891. * Move the current animation to a given frame
  50892. * @param frame defines the frame to move to
  50893. */
  50894. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50895. var keys = this._animation.getKeys();
  50896. if (frame < keys[0].frame) {
  50897. frame = keys[0].frame;
  50898. }
  50899. else if (frame > keys[keys.length - 1].frame) {
  50900. frame = keys[keys.length - 1].frame;
  50901. }
  50902. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50903. this.setValue(currentValue, -1);
  50904. };
  50905. /**
  50906. * @hidden Internal use only
  50907. */
  50908. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  50909. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  50910. this._ratioOffset = this._previousRatio - newRatio;
  50911. };
  50912. /**
  50913. * Execute the current animation
  50914. * @param delay defines the delay to add to the current frame
  50915. * @param from defines the lower bound of the animation range
  50916. * @param to defines the upper bound of the animation range
  50917. * @param loop defines if the current animation must loop
  50918. * @param speedRatio defines the current speed ratio
  50919. * @param weight defines the weight of the animation (default is -1 so no weight)
  50920. * @returns a boolean indicating if the animation is running
  50921. */
  50922. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  50923. if (weight === void 0) { weight = -1.0; }
  50924. var targetPropertyPath = this._animation.targetPropertyPath;
  50925. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  50926. this._stopped = true;
  50927. return false;
  50928. }
  50929. var returnValue = true;
  50930. var keys = this._animation.getKeys();
  50931. // Adding a start key at frame 0 if missing
  50932. if (keys[0].frame !== 0) {
  50933. var newKey = { frame: 0, value: keys[0].value };
  50934. keys.splice(0, 0, newKey);
  50935. }
  50936. // Adding a duplicate key when there is only one key at frame zero
  50937. else if (keys.length === 1) {
  50938. var newKey = { frame: 0.001, value: keys[0].value };
  50939. keys.push(newKey);
  50940. }
  50941. // Check limits
  50942. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  50943. from = keys[0].frame;
  50944. }
  50945. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  50946. to = keys[keys.length - 1].frame;
  50947. }
  50948. //to and from cannot be the same key
  50949. if (from === to) {
  50950. if (from > keys[0].frame) {
  50951. from--;
  50952. }
  50953. else if (to < keys[keys.length - 1].frame) {
  50954. to++;
  50955. }
  50956. }
  50957. // Compute ratio
  50958. var range = to - from;
  50959. var offsetValue;
  50960. // ratio represents the frame delta between from and to
  50961. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  50962. var highLimitValue = 0;
  50963. this._previousDelay = delay;
  50964. this._previousRatio = ratio;
  50965. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  50966. returnValue = false;
  50967. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  50968. }
  50969. else {
  50970. // Get max value if required
  50971. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  50972. var keyOffset = to.toString() + from.toString();
  50973. if (!this._offsetsCache[keyOffset]) {
  50974. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50975. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  50976. switch (this._animation.dataType) {
  50977. // Float
  50978. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  50979. this._offsetsCache[keyOffset] = toValue - fromValue;
  50980. break;
  50981. // Quaternion
  50982. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  50983. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50984. break;
  50985. // Vector3
  50986. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  50987. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50988. // Vector2
  50989. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  50990. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50991. // Size
  50992. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  50993. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50994. // Color3
  50995. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  50996. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  50997. default:
  50998. break;
  50999. }
  51000. this._highLimitsCache[keyOffset] = toValue;
  51001. }
  51002. highLimitValue = this._highLimitsCache[keyOffset];
  51003. offsetValue = this._offsetsCache[keyOffset];
  51004. }
  51005. }
  51006. if (offsetValue === undefined) {
  51007. switch (this._animation.dataType) {
  51008. // Float
  51009. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51010. offsetValue = 0;
  51011. break;
  51012. // Quaternion
  51013. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51014. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51015. break;
  51016. // Vector3
  51017. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51018. offsetValue = BABYLON.Vector3.Zero();
  51019. break;
  51020. // Vector2
  51021. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51022. offsetValue = BABYLON.Vector2.Zero();
  51023. break;
  51024. // Size
  51025. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51026. offsetValue = BABYLON.Size.Zero();
  51027. break;
  51028. // Color3
  51029. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51030. offsetValue = BABYLON.Color3.Black();
  51031. }
  51032. }
  51033. // Compute value
  51034. var repeatCount = (ratio / range) >> 0;
  51035. var currentFrame = returnValue ? from + ratio % range : to;
  51036. // Need to normalize?
  51037. if (this._host && this._host.syncRoot) {
  51038. var syncRoot = this._host.syncRoot;
  51039. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51040. currentFrame = from + (to - from) * hostNormalizedFrame;
  51041. }
  51042. // Reset events if looping
  51043. var events = this._events;
  51044. if (range > 0 && this.currentFrame > currentFrame ||
  51045. range < 0 && this.currentFrame < currentFrame) {
  51046. // Need to reset animation events
  51047. for (var index = 0; index < events.length; index++) {
  51048. if (!events[index].onlyOnce) {
  51049. // reset event, the animation is looping
  51050. events[index].isDone = false;
  51051. }
  51052. }
  51053. }
  51054. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51055. // Set value
  51056. this.setValue(currentValue, weight);
  51057. // Check events
  51058. for (var index = 0; index < events.length; index++) {
  51059. // Make sure current frame has passed event frame and that event frame is within the current range
  51060. // Also, handle both forward and reverse animations
  51061. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51062. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51063. var event = events[index];
  51064. if (!event.isDone) {
  51065. // If event should be done only once, remove it.
  51066. if (event.onlyOnce) {
  51067. events.splice(index, 1);
  51068. index--;
  51069. }
  51070. event.isDone = true;
  51071. event.action();
  51072. } // Don't do anything if the event has already be done.
  51073. }
  51074. }
  51075. if (!returnValue) {
  51076. this._stopped = true;
  51077. }
  51078. return returnValue;
  51079. };
  51080. return RuntimeAnimation;
  51081. }());
  51082. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51083. })(BABYLON || (BABYLON = {}));
  51084. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51085. var BABYLON;
  51086. (function (BABYLON) {
  51087. /**
  51088. * Class used to store an actual running animation
  51089. */
  51090. var Animatable = /** @class */ (function () {
  51091. /**
  51092. * Creates a new Animatable
  51093. * @param scene defines the hosting scene
  51094. * @param target defines the target object
  51095. * @param fromFrame defines the starting frame number (default is 0)
  51096. * @param toFrame defines the ending frame number (default is 100)
  51097. * @param loopAnimation defines if the animation must loop (default is false)
  51098. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51099. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51100. * @param animations defines a group of animation to add to the new Animatable
  51101. */
  51102. function Animatable(scene,
  51103. /** defines the target object */
  51104. target,
  51105. /** defines the starting frame number (default is 0) */
  51106. fromFrame,
  51107. /** defines the ending frame number (default is 100) */
  51108. toFrame,
  51109. /** defines if the animation must loop (default is false) */
  51110. loopAnimation, speedRatio,
  51111. /** defines a callback to call when animation ends if it is not looping */
  51112. onAnimationEnd, animations) {
  51113. if (fromFrame === void 0) { fromFrame = 0; }
  51114. if (toFrame === void 0) { toFrame = 100; }
  51115. if (loopAnimation === void 0) { loopAnimation = false; }
  51116. if (speedRatio === void 0) { speedRatio = 1.0; }
  51117. this.target = target;
  51118. this.fromFrame = fromFrame;
  51119. this.toFrame = toFrame;
  51120. this.loopAnimation = loopAnimation;
  51121. this.onAnimationEnd = onAnimationEnd;
  51122. this._localDelayOffset = null;
  51123. this._pausedDelay = null;
  51124. this._runtimeAnimations = new Array();
  51125. this._paused = false;
  51126. this._speedRatio = 1;
  51127. this._weight = -1.0;
  51128. /**
  51129. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51130. * This will only apply for non looping animation (default is true)
  51131. */
  51132. this.disposeOnEnd = true;
  51133. /**
  51134. * Gets a boolean indicating if the animation has started
  51135. */
  51136. this.animationStarted = false;
  51137. /**
  51138. * Observer raised when the animation ends
  51139. */
  51140. this.onAnimationEndObservable = new BABYLON.Observable();
  51141. this._scene = scene;
  51142. if (animations) {
  51143. this.appendAnimations(target, animations);
  51144. }
  51145. this._speedRatio = speedRatio;
  51146. scene._activeAnimatables.push(this);
  51147. }
  51148. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51149. /**
  51150. * Gets the root Animatable used to synchronize and normalize animations
  51151. */
  51152. get: function () {
  51153. return this._syncRoot;
  51154. },
  51155. enumerable: true,
  51156. configurable: true
  51157. });
  51158. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51159. /**
  51160. * Gets the current frame of the first RuntimeAnimation
  51161. * Used to synchronize Animatables
  51162. */
  51163. get: function () {
  51164. if (this._runtimeAnimations.length === 0) {
  51165. return 0;
  51166. }
  51167. return this._runtimeAnimations[0].currentFrame;
  51168. },
  51169. enumerable: true,
  51170. configurable: true
  51171. });
  51172. Object.defineProperty(Animatable.prototype, "weight", {
  51173. /**
  51174. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51175. */
  51176. get: function () {
  51177. return this._weight;
  51178. },
  51179. set: function (value) {
  51180. if (value === -1) { // -1 is ok and means no weight
  51181. this._weight = -1;
  51182. return;
  51183. }
  51184. // Else weight must be in [0, 1] range
  51185. this._weight = Math.min(Math.max(value, 0), 1.0);
  51186. },
  51187. enumerable: true,
  51188. configurable: true
  51189. });
  51190. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51191. /**
  51192. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51193. */
  51194. get: function () {
  51195. return this._speedRatio;
  51196. },
  51197. set: function (value) {
  51198. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51199. var animation = this._runtimeAnimations[index];
  51200. animation._prepareForSpeedRatioChange(value);
  51201. }
  51202. this._speedRatio = value;
  51203. },
  51204. enumerable: true,
  51205. configurable: true
  51206. });
  51207. // Methods
  51208. /**
  51209. * Synchronize and normalize current Animatable with a source Animatable
  51210. * This is useful when using animation weights and when animations are not of the same length
  51211. * @param root defines the root Animatable to synchronize with
  51212. * @returns the current Animatable
  51213. */
  51214. Animatable.prototype.syncWith = function (root) {
  51215. this._syncRoot = root;
  51216. if (root) {
  51217. // Make sure this animatable will animate after the root
  51218. var index = this._scene._activeAnimatables.indexOf(this);
  51219. if (index > -1) {
  51220. this._scene._activeAnimatables.splice(index, 1);
  51221. this._scene._activeAnimatables.push(this);
  51222. }
  51223. }
  51224. return this;
  51225. };
  51226. /**
  51227. * Gets the list of runtime animations
  51228. * @returns an array of RuntimeAnimation
  51229. */
  51230. Animatable.prototype.getAnimations = function () {
  51231. return this._runtimeAnimations;
  51232. };
  51233. /**
  51234. * Adds more animations to the current animatable
  51235. * @param target defines the target of the animations
  51236. * @param animations defines the new animations to add
  51237. */
  51238. Animatable.prototype.appendAnimations = function (target, animations) {
  51239. for (var index = 0; index < animations.length; index++) {
  51240. var animation = animations[index];
  51241. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51242. }
  51243. };
  51244. /**
  51245. * Gets the source animation for a specific property
  51246. * @param property defines the propertyu to look for
  51247. * @returns null or the source animation for the given property
  51248. */
  51249. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51250. var runtimeAnimations = this._runtimeAnimations;
  51251. for (var index = 0; index < runtimeAnimations.length; index++) {
  51252. if (runtimeAnimations[index].animation.targetProperty === property) {
  51253. return runtimeAnimations[index].animation;
  51254. }
  51255. }
  51256. return null;
  51257. };
  51258. /**
  51259. * Gets the runtime animation for a specific property
  51260. * @param property defines the propertyu to look for
  51261. * @returns null or the runtime animation for the given property
  51262. */
  51263. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51264. var runtimeAnimations = this._runtimeAnimations;
  51265. for (var index = 0; index < runtimeAnimations.length; index++) {
  51266. if (runtimeAnimations[index].animation.targetProperty === property) {
  51267. return runtimeAnimations[index];
  51268. }
  51269. }
  51270. return null;
  51271. };
  51272. /**
  51273. * Resets the animatable to its original state
  51274. */
  51275. Animatable.prototype.reset = function () {
  51276. var runtimeAnimations = this._runtimeAnimations;
  51277. for (var index = 0; index < runtimeAnimations.length; index++) {
  51278. runtimeAnimations[index].reset(true);
  51279. }
  51280. this._localDelayOffset = null;
  51281. this._pausedDelay = null;
  51282. };
  51283. /**
  51284. * Allows the animatable to blend with current running animations
  51285. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51286. * @param blendingSpeed defines the blending speed to use
  51287. */
  51288. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51289. var runtimeAnimations = this._runtimeAnimations;
  51290. for (var index = 0; index < runtimeAnimations.length; index++) {
  51291. runtimeAnimations[index].animation.enableBlending = true;
  51292. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51293. }
  51294. };
  51295. /**
  51296. * Disable animation blending
  51297. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51298. */
  51299. Animatable.prototype.disableBlending = function () {
  51300. var runtimeAnimations = this._runtimeAnimations;
  51301. for (var index = 0; index < runtimeAnimations.length; index++) {
  51302. runtimeAnimations[index].animation.enableBlending = false;
  51303. }
  51304. };
  51305. /**
  51306. * Jump directly to a given frame
  51307. * @param frame defines the frame to jump to
  51308. */
  51309. Animatable.prototype.goToFrame = function (frame) {
  51310. var runtimeAnimations = this._runtimeAnimations;
  51311. if (runtimeAnimations[0]) {
  51312. var fps = runtimeAnimations[0].animation.framePerSecond;
  51313. var currentFrame = runtimeAnimations[0].currentFrame;
  51314. var adjustTime = frame - currentFrame;
  51315. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51316. if (this._localDelayOffset === null) {
  51317. this._localDelayOffset = 0;
  51318. }
  51319. this._localDelayOffset -= delay;
  51320. }
  51321. for (var index = 0; index < runtimeAnimations.length; index++) {
  51322. runtimeAnimations[index].goToFrame(frame);
  51323. }
  51324. };
  51325. /**
  51326. * Pause the animation
  51327. */
  51328. Animatable.prototype.pause = function () {
  51329. if (this._paused) {
  51330. return;
  51331. }
  51332. this._paused = true;
  51333. };
  51334. /**
  51335. * Restart the animation
  51336. */
  51337. Animatable.prototype.restart = function () {
  51338. this._paused = false;
  51339. };
  51340. Animatable.prototype._raiseOnAnimationEnd = function () {
  51341. if (this.onAnimationEnd) {
  51342. this.onAnimationEnd();
  51343. }
  51344. this.onAnimationEndObservable.notifyObservers(this);
  51345. };
  51346. /**
  51347. * Stop and delete the current animation
  51348. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51349. * @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)
  51350. */
  51351. Animatable.prototype.stop = function (animationName, targetMask) {
  51352. if (animationName || targetMask) {
  51353. var idx = this._scene._activeAnimatables.indexOf(this);
  51354. if (idx > -1) {
  51355. var runtimeAnimations = this._runtimeAnimations;
  51356. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51357. var runtimeAnimation = runtimeAnimations[index];
  51358. if (animationName && runtimeAnimation.animation.name != animationName) {
  51359. continue;
  51360. }
  51361. if (targetMask && !targetMask(runtimeAnimation.target)) {
  51362. continue;
  51363. }
  51364. runtimeAnimation.dispose();
  51365. runtimeAnimations.splice(index, 1);
  51366. }
  51367. if (runtimeAnimations.length == 0) {
  51368. this._scene._activeAnimatables.splice(idx, 1);
  51369. this._raiseOnAnimationEnd();
  51370. }
  51371. }
  51372. }
  51373. else {
  51374. var index = this._scene._activeAnimatables.indexOf(this);
  51375. if (index > -1) {
  51376. this._scene._activeAnimatables.splice(index, 1);
  51377. var runtimeAnimations = this._runtimeAnimations;
  51378. for (var index = 0; index < runtimeAnimations.length; index++) {
  51379. runtimeAnimations[index].dispose();
  51380. }
  51381. this._raiseOnAnimationEnd();
  51382. }
  51383. }
  51384. };
  51385. /**
  51386. * Wait asynchronously for the animation to end
  51387. * @returns a promise which will be fullfilled when the animation ends
  51388. */
  51389. Animatable.prototype.waitAsync = function () {
  51390. var _this = this;
  51391. return new Promise(function (resolve, reject) {
  51392. _this.onAnimationEndObservable.add(function () {
  51393. resolve(_this);
  51394. }, undefined, undefined, _this, true);
  51395. });
  51396. };
  51397. /** @hidden */
  51398. Animatable.prototype._animate = function (delay) {
  51399. if (this._paused) {
  51400. this.animationStarted = false;
  51401. if (this._pausedDelay === null) {
  51402. this._pausedDelay = delay;
  51403. }
  51404. return true;
  51405. }
  51406. if (this._localDelayOffset === null) {
  51407. this._localDelayOffset = delay;
  51408. this._pausedDelay = null;
  51409. }
  51410. else if (this._pausedDelay !== null) {
  51411. this._localDelayOffset += delay - this._pausedDelay;
  51412. this._pausedDelay = null;
  51413. }
  51414. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51415. return true;
  51416. }
  51417. // Animating
  51418. var running = false;
  51419. var runtimeAnimations = this._runtimeAnimations;
  51420. var index;
  51421. for (index = 0; index < runtimeAnimations.length; index++) {
  51422. var animation = runtimeAnimations[index];
  51423. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51424. running = running || isRunning;
  51425. }
  51426. this.animationStarted = running;
  51427. if (!running) {
  51428. if (this.disposeOnEnd) {
  51429. // Remove from active animatables
  51430. index = this._scene._activeAnimatables.indexOf(this);
  51431. this._scene._activeAnimatables.splice(index, 1);
  51432. // Dispose all runtime animations
  51433. for (index = 0; index < runtimeAnimations.length; index++) {
  51434. runtimeAnimations[index].dispose();
  51435. }
  51436. }
  51437. this._raiseOnAnimationEnd();
  51438. if (this.disposeOnEnd) {
  51439. this.onAnimationEnd = null;
  51440. this.onAnimationEndObservable.clear();
  51441. }
  51442. }
  51443. return running;
  51444. };
  51445. return Animatable;
  51446. }());
  51447. BABYLON.Animatable = Animatable;
  51448. })(BABYLON || (BABYLON = {}));
  51449. //# sourceMappingURL=babylon.animatable.js.map
  51450. var BABYLON;
  51451. (function (BABYLON) {
  51452. var EasingFunction = /** @class */ (function () {
  51453. function EasingFunction() {
  51454. // Properties
  51455. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51456. }
  51457. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51458. get: function () {
  51459. return EasingFunction._EASINGMODE_EASEIN;
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51465. get: function () {
  51466. return EasingFunction._EASINGMODE_EASEOUT;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51472. get: function () {
  51473. return EasingFunction._EASINGMODE_EASEINOUT;
  51474. },
  51475. enumerable: true,
  51476. configurable: true
  51477. });
  51478. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51479. var n = Math.min(Math.max(easingMode, 0), 2);
  51480. this._easingMode = n;
  51481. };
  51482. EasingFunction.prototype.getEasingMode = function () {
  51483. return this._easingMode;
  51484. };
  51485. EasingFunction.prototype.easeInCore = function (gradient) {
  51486. throw new Error('You must implement this method');
  51487. };
  51488. EasingFunction.prototype.ease = function (gradient) {
  51489. switch (this._easingMode) {
  51490. case EasingFunction.EASINGMODE_EASEIN:
  51491. return this.easeInCore(gradient);
  51492. case EasingFunction.EASINGMODE_EASEOUT:
  51493. return (1 - this.easeInCore(1 - gradient));
  51494. }
  51495. if (gradient >= 0.5) {
  51496. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51497. }
  51498. return (this.easeInCore(gradient * 2) * 0.5);
  51499. };
  51500. //Statics
  51501. EasingFunction._EASINGMODE_EASEIN = 0;
  51502. EasingFunction._EASINGMODE_EASEOUT = 1;
  51503. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51504. return EasingFunction;
  51505. }());
  51506. BABYLON.EasingFunction = EasingFunction;
  51507. var CircleEase = /** @class */ (function (_super) {
  51508. __extends(CircleEase, _super);
  51509. function CircleEase() {
  51510. return _super !== null && _super.apply(this, arguments) || this;
  51511. }
  51512. CircleEase.prototype.easeInCore = function (gradient) {
  51513. gradient = Math.max(0, Math.min(1, gradient));
  51514. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51515. };
  51516. return CircleEase;
  51517. }(EasingFunction));
  51518. BABYLON.CircleEase = CircleEase;
  51519. var BackEase = /** @class */ (function (_super) {
  51520. __extends(BackEase, _super);
  51521. function BackEase(amplitude) {
  51522. if (amplitude === void 0) { amplitude = 1; }
  51523. var _this = _super.call(this) || this;
  51524. _this.amplitude = amplitude;
  51525. return _this;
  51526. }
  51527. BackEase.prototype.easeInCore = function (gradient) {
  51528. var num = Math.max(0, this.amplitude);
  51529. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51530. };
  51531. return BackEase;
  51532. }(EasingFunction));
  51533. BABYLON.BackEase = BackEase;
  51534. var BounceEase = /** @class */ (function (_super) {
  51535. __extends(BounceEase, _super);
  51536. function BounceEase(bounces, bounciness) {
  51537. if (bounces === void 0) { bounces = 3; }
  51538. if (bounciness === void 0) { bounciness = 2; }
  51539. var _this = _super.call(this) || this;
  51540. _this.bounces = bounces;
  51541. _this.bounciness = bounciness;
  51542. return _this;
  51543. }
  51544. BounceEase.prototype.easeInCore = function (gradient) {
  51545. var y = Math.max(0.0, this.bounces);
  51546. var bounciness = this.bounciness;
  51547. if (bounciness <= 1.0) {
  51548. bounciness = 1.001;
  51549. }
  51550. var num9 = Math.pow(bounciness, y);
  51551. var num5 = 1.0 - bounciness;
  51552. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51553. var num15 = gradient * num4;
  51554. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51555. var num3 = Math.floor(num65);
  51556. var num13 = num3 + 1.0;
  51557. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51558. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51559. var num7 = (num8 + num12) * 0.5;
  51560. var num6 = gradient - num7;
  51561. var num2 = num7 - num8;
  51562. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51563. };
  51564. return BounceEase;
  51565. }(EasingFunction));
  51566. BABYLON.BounceEase = BounceEase;
  51567. var CubicEase = /** @class */ (function (_super) {
  51568. __extends(CubicEase, _super);
  51569. function CubicEase() {
  51570. return _super !== null && _super.apply(this, arguments) || this;
  51571. }
  51572. CubicEase.prototype.easeInCore = function (gradient) {
  51573. return (gradient * gradient * gradient);
  51574. };
  51575. return CubicEase;
  51576. }(EasingFunction));
  51577. BABYLON.CubicEase = CubicEase;
  51578. var ElasticEase = /** @class */ (function (_super) {
  51579. __extends(ElasticEase, _super);
  51580. function ElasticEase(oscillations, springiness) {
  51581. if (oscillations === void 0) { oscillations = 3; }
  51582. if (springiness === void 0) { springiness = 3; }
  51583. var _this = _super.call(this) || this;
  51584. _this.oscillations = oscillations;
  51585. _this.springiness = springiness;
  51586. return _this;
  51587. }
  51588. ElasticEase.prototype.easeInCore = function (gradient) {
  51589. var num2;
  51590. var num3 = Math.max(0.0, this.oscillations);
  51591. var num = Math.max(0.0, this.springiness);
  51592. if (num == 0) {
  51593. num2 = gradient;
  51594. }
  51595. else {
  51596. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51597. }
  51598. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51599. };
  51600. return ElasticEase;
  51601. }(EasingFunction));
  51602. BABYLON.ElasticEase = ElasticEase;
  51603. var ExponentialEase = /** @class */ (function (_super) {
  51604. __extends(ExponentialEase, _super);
  51605. function ExponentialEase(exponent) {
  51606. if (exponent === void 0) { exponent = 2; }
  51607. var _this = _super.call(this) || this;
  51608. _this.exponent = exponent;
  51609. return _this;
  51610. }
  51611. ExponentialEase.prototype.easeInCore = function (gradient) {
  51612. if (this.exponent <= 0) {
  51613. return gradient;
  51614. }
  51615. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51616. };
  51617. return ExponentialEase;
  51618. }(EasingFunction));
  51619. BABYLON.ExponentialEase = ExponentialEase;
  51620. var PowerEase = /** @class */ (function (_super) {
  51621. __extends(PowerEase, _super);
  51622. function PowerEase(power) {
  51623. if (power === void 0) { power = 2; }
  51624. var _this = _super.call(this) || this;
  51625. _this.power = power;
  51626. return _this;
  51627. }
  51628. PowerEase.prototype.easeInCore = function (gradient) {
  51629. var y = Math.max(0.0, this.power);
  51630. return Math.pow(gradient, y);
  51631. };
  51632. return PowerEase;
  51633. }(EasingFunction));
  51634. BABYLON.PowerEase = PowerEase;
  51635. var QuadraticEase = /** @class */ (function (_super) {
  51636. __extends(QuadraticEase, _super);
  51637. function QuadraticEase() {
  51638. return _super !== null && _super.apply(this, arguments) || this;
  51639. }
  51640. QuadraticEase.prototype.easeInCore = function (gradient) {
  51641. return (gradient * gradient);
  51642. };
  51643. return QuadraticEase;
  51644. }(EasingFunction));
  51645. BABYLON.QuadraticEase = QuadraticEase;
  51646. var QuarticEase = /** @class */ (function (_super) {
  51647. __extends(QuarticEase, _super);
  51648. function QuarticEase() {
  51649. return _super !== null && _super.apply(this, arguments) || this;
  51650. }
  51651. QuarticEase.prototype.easeInCore = function (gradient) {
  51652. return (gradient * gradient * gradient * gradient);
  51653. };
  51654. return QuarticEase;
  51655. }(EasingFunction));
  51656. BABYLON.QuarticEase = QuarticEase;
  51657. var QuinticEase = /** @class */ (function (_super) {
  51658. __extends(QuinticEase, _super);
  51659. function QuinticEase() {
  51660. return _super !== null && _super.apply(this, arguments) || this;
  51661. }
  51662. QuinticEase.prototype.easeInCore = function (gradient) {
  51663. return (gradient * gradient * gradient * gradient * gradient);
  51664. };
  51665. return QuinticEase;
  51666. }(EasingFunction));
  51667. BABYLON.QuinticEase = QuinticEase;
  51668. var SineEase = /** @class */ (function (_super) {
  51669. __extends(SineEase, _super);
  51670. function SineEase() {
  51671. return _super !== null && _super.apply(this, arguments) || this;
  51672. }
  51673. SineEase.prototype.easeInCore = function (gradient) {
  51674. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51675. };
  51676. return SineEase;
  51677. }(EasingFunction));
  51678. BABYLON.SineEase = SineEase;
  51679. var BezierCurveEase = /** @class */ (function (_super) {
  51680. __extends(BezierCurveEase, _super);
  51681. function BezierCurveEase(x1, y1, x2, y2) {
  51682. if (x1 === void 0) { x1 = 0; }
  51683. if (y1 === void 0) { y1 = 0; }
  51684. if (x2 === void 0) { x2 = 1; }
  51685. if (y2 === void 0) { y2 = 1; }
  51686. var _this = _super.call(this) || this;
  51687. _this.x1 = x1;
  51688. _this.y1 = y1;
  51689. _this.x2 = x2;
  51690. _this.y2 = y2;
  51691. return _this;
  51692. }
  51693. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51694. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51695. };
  51696. return BezierCurveEase;
  51697. }(EasingFunction));
  51698. BABYLON.BezierCurveEase = BezierCurveEase;
  51699. })(BABYLON || (BABYLON = {}));
  51700. //# sourceMappingURL=babylon.easing.js.map
  51701. var BABYLON;
  51702. (function (BABYLON) {
  51703. /**
  51704. * A Condition applied to an Action
  51705. */
  51706. var Condition = /** @class */ (function () {
  51707. /**
  51708. * Creates a new Condition
  51709. * @param actionManager the manager of the action the condition is applied to
  51710. */
  51711. function Condition(actionManager) {
  51712. this._actionManager = actionManager;
  51713. }
  51714. /**
  51715. * Check if the current condition is valid
  51716. * @returns a boolean
  51717. */
  51718. Condition.prototype.isValid = function () {
  51719. return true;
  51720. };
  51721. /**
  51722. * Internal only
  51723. * @hidden
  51724. */
  51725. Condition.prototype._getProperty = function (propertyPath) {
  51726. return this._actionManager._getProperty(propertyPath);
  51727. };
  51728. /**
  51729. * Internal only
  51730. * @hidden
  51731. */
  51732. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51733. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51734. };
  51735. /**
  51736. * Serialize placeholder for child classes
  51737. * @returns the serialized object
  51738. */
  51739. Condition.prototype.serialize = function () {
  51740. };
  51741. /**
  51742. * Internal only
  51743. * @hidden
  51744. */
  51745. Condition.prototype._serialize = function (serializedCondition) {
  51746. return {
  51747. type: 2,
  51748. children: [],
  51749. name: serializedCondition.name,
  51750. properties: serializedCondition.properties
  51751. };
  51752. };
  51753. return Condition;
  51754. }());
  51755. BABYLON.Condition = Condition;
  51756. /**
  51757. * Defines specific conditional operators as extensions of Condition
  51758. */
  51759. var ValueCondition = /** @class */ (function (_super) {
  51760. __extends(ValueCondition, _super);
  51761. /**
  51762. * Creates a new ValueCondition
  51763. * @param actionManager manager for the action the condition applies to
  51764. * @param target for the action
  51765. * @param propertyPath path to specify the property of the target the conditional operator uses
  51766. * @param value the value compared by the conditional operator against the current value of the property
  51767. * @param operator the conditional operator, default ValueCondition.IsEqual
  51768. */
  51769. function ValueCondition(actionManager, target,
  51770. /** path to specify the property of the target the conditional operator uses */
  51771. propertyPath,
  51772. /** the value compared by the conditional operator against the current value of the property */
  51773. value,
  51774. /** the conditional operator, default ValueCondition.IsEqual */
  51775. operator) {
  51776. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51777. var _this = _super.call(this, actionManager) || this;
  51778. _this.propertyPath = propertyPath;
  51779. _this.value = value;
  51780. _this.operator = operator;
  51781. _this._target = target;
  51782. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51783. _this._property = _this._getProperty(_this.propertyPath);
  51784. return _this;
  51785. }
  51786. Object.defineProperty(ValueCondition, "IsEqual", {
  51787. /**
  51788. * returns the number for IsEqual
  51789. */
  51790. get: function () {
  51791. return ValueCondition._IsEqual;
  51792. },
  51793. enumerable: true,
  51794. configurable: true
  51795. });
  51796. Object.defineProperty(ValueCondition, "IsDifferent", {
  51797. /**
  51798. * Returns the number for IsDifferent
  51799. */
  51800. get: function () {
  51801. return ValueCondition._IsDifferent;
  51802. },
  51803. enumerable: true,
  51804. configurable: true
  51805. });
  51806. Object.defineProperty(ValueCondition, "IsGreater", {
  51807. /**
  51808. * Returns the number for IsGreater
  51809. */
  51810. get: function () {
  51811. return ValueCondition._IsGreater;
  51812. },
  51813. enumerable: true,
  51814. configurable: true
  51815. });
  51816. Object.defineProperty(ValueCondition, "IsLesser", {
  51817. /**
  51818. * Returns the number for IsLesser
  51819. */
  51820. get: function () {
  51821. return ValueCondition._IsLesser;
  51822. },
  51823. enumerable: true,
  51824. configurable: true
  51825. });
  51826. /**
  51827. * Compares the given value with the property value for the specified conditional operator
  51828. * @returns the result of the comparison
  51829. */
  51830. ValueCondition.prototype.isValid = function () {
  51831. switch (this.operator) {
  51832. case ValueCondition.IsGreater:
  51833. return this._effectiveTarget[this._property] > this.value;
  51834. case ValueCondition.IsLesser:
  51835. return this._effectiveTarget[this._property] < this.value;
  51836. case ValueCondition.IsEqual:
  51837. case ValueCondition.IsDifferent:
  51838. var check;
  51839. if (this.value.equals) {
  51840. check = this.value.equals(this._effectiveTarget[this._property]);
  51841. }
  51842. else {
  51843. check = this.value === this._effectiveTarget[this._property];
  51844. }
  51845. return this.operator === ValueCondition.IsEqual ? check : !check;
  51846. }
  51847. return false;
  51848. };
  51849. /**
  51850. * Serialize the ValueCondition into a JSON compatible object
  51851. * @returns serialization object
  51852. */
  51853. ValueCondition.prototype.serialize = function () {
  51854. return this._serialize({
  51855. name: "ValueCondition",
  51856. properties: [
  51857. BABYLON.Action._GetTargetProperty(this._target),
  51858. { name: "propertyPath", value: this.propertyPath },
  51859. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51860. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51861. ]
  51862. });
  51863. };
  51864. /**
  51865. * Gets the name of the conditional operator for the ValueCondition
  51866. * @param operator the conditional operator
  51867. * @returns the name
  51868. */
  51869. ValueCondition.GetOperatorName = function (operator) {
  51870. switch (operator) {
  51871. case ValueCondition._IsEqual: return "IsEqual";
  51872. case ValueCondition._IsDifferent: return "IsDifferent";
  51873. case ValueCondition._IsGreater: return "IsGreater";
  51874. case ValueCondition._IsLesser: return "IsLesser";
  51875. default: return "";
  51876. }
  51877. };
  51878. /**
  51879. * Internal only
  51880. * @hidden
  51881. */
  51882. ValueCondition._IsEqual = 0;
  51883. /**
  51884. * Internal only
  51885. * @hidden
  51886. */
  51887. ValueCondition._IsDifferent = 1;
  51888. /**
  51889. * Internal only
  51890. * @hidden
  51891. */
  51892. ValueCondition._IsGreater = 2;
  51893. /**
  51894. * Internal only
  51895. * @hidden
  51896. */
  51897. ValueCondition._IsLesser = 3;
  51898. return ValueCondition;
  51899. }(Condition));
  51900. BABYLON.ValueCondition = ValueCondition;
  51901. /**
  51902. * Defines a predicate condition as an extension of Condition
  51903. */
  51904. var PredicateCondition = /** @class */ (function (_super) {
  51905. __extends(PredicateCondition, _super);
  51906. /**
  51907. * Creates a new PredicateCondition
  51908. * @param actionManager manager for the action the condition applies to
  51909. * @param predicate defines the predicate function used to validate the condition
  51910. */
  51911. function PredicateCondition(actionManager,
  51912. /** defines the predicate function used to validate the condition */
  51913. predicate) {
  51914. var _this = _super.call(this, actionManager) || this;
  51915. _this.predicate = predicate;
  51916. return _this;
  51917. }
  51918. /**
  51919. * @returns the validity of the predicate condition
  51920. */
  51921. PredicateCondition.prototype.isValid = function () {
  51922. return this.predicate();
  51923. };
  51924. return PredicateCondition;
  51925. }(Condition));
  51926. BABYLON.PredicateCondition = PredicateCondition;
  51927. /**
  51928. * Defines a state condition as an extension of Condition
  51929. */
  51930. var StateCondition = /** @class */ (function (_super) {
  51931. __extends(StateCondition, _super);
  51932. /**
  51933. * Creates a new StateCondition
  51934. * @param actionManager manager for the action the condition applies to
  51935. * @param target of the condition
  51936. * @param value to compare with target state
  51937. */
  51938. function StateCondition(actionManager, target, value) {
  51939. var _this = _super.call(this, actionManager) || this;
  51940. _this.value = value;
  51941. _this._target = target;
  51942. return _this;
  51943. }
  51944. /**
  51945. * @returns the validity of the state
  51946. */
  51947. StateCondition.prototype.isValid = function () {
  51948. return this._target.state === this.value;
  51949. };
  51950. /**
  51951. * Serialize the StateCondition into a JSON compatible object
  51952. * @returns serialization object
  51953. */
  51954. StateCondition.prototype.serialize = function () {
  51955. return this._serialize({
  51956. name: "StateCondition",
  51957. properties: [
  51958. BABYLON.Action._GetTargetProperty(this._target),
  51959. { name: "value", value: this.value }
  51960. ]
  51961. });
  51962. };
  51963. return StateCondition;
  51964. }(Condition));
  51965. BABYLON.StateCondition = StateCondition;
  51966. })(BABYLON || (BABYLON = {}));
  51967. //# sourceMappingURL=babylon.condition.js.map
  51968. var BABYLON;
  51969. (function (BABYLON) {
  51970. /**
  51971. * The action to be carried out following a trigger
  51972. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  51973. */
  51974. var Action = /** @class */ (function () {
  51975. /**
  51976. * Creates a new Action
  51977. * @param triggerOptions the trigger, with or without parameters, for the action
  51978. * @param condition an optional determinant of action
  51979. */
  51980. function Action(
  51981. /** the trigger, with or without parameters, for the action */
  51982. triggerOptions, condition) {
  51983. this.triggerOptions = triggerOptions;
  51984. /**
  51985. * An event triggered prior to action being executed.
  51986. */
  51987. this.onBeforeExecuteObservable = new BABYLON.Observable();
  51988. if (triggerOptions.parameter) {
  51989. this.trigger = triggerOptions.trigger;
  51990. this._triggerParameter = triggerOptions.parameter;
  51991. }
  51992. else {
  51993. this.trigger = triggerOptions;
  51994. }
  51995. this._nextActiveAction = this;
  51996. this._condition = condition;
  51997. }
  51998. /**
  51999. * Internal only
  52000. * @hidden
  52001. */
  52002. Action.prototype._prepare = function () {
  52003. };
  52004. /**
  52005. * Gets the trigger parameters
  52006. * @returns the trigger parameters
  52007. */
  52008. Action.prototype.getTriggerParameter = function () {
  52009. return this._triggerParameter;
  52010. };
  52011. /**
  52012. * Internal only - executes current action event
  52013. * @hidden
  52014. */
  52015. Action.prototype._executeCurrent = function (evt) {
  52016. if (this._nextActiveAction._condition) {
  52017. var condition = this._nextActiveAction._condition;
  52018. var currentRenderId = this._actionManager.getScene().getRenderId();
  52019. // We cache the current evaluation for the current frame
  52020. if (condition._evaluationId === currentRenderId) {
  52021. if (!condition._currentResult) {
  52022. return;
  52023. }
  52024. }
  52025. else {
  52026. condition._evaluationId = currentRenderId;
  52027. if (!condition.isValid()) {
  52028. condition._currentResult = false;
  52029. return;
  52030. }
  52031. condition._currentResult = true;
  52032. }
  52033. }
  52034. this.onBeforeExecuteObservable.notifyObservers(this);
  52035. this._nextActiveAction.execute(evt);
  52036. this.skipToNextActiveAction();
  52037. };
  52038. /**
  52039. * Execute placeholder for child classes
  52040. * @param evt optional action event
  52041. */
  52042. Action.prototype.execute = function (evt) {
  52043. };
  52044. /**
  52045. * Skips to next active action
  52046. */
  52047. Action.prototype.skipToNextActiveAction = function () {
  52048. if (this._nextActiveAction._child) {
  52049. if (!this._nextActiveAction._child._actionManager) {
  52050. this._nextActiveAction._child._actionManager = this._actionManager;
  52051. }
  52052. this._nextActiveAction = this._nextActiveAction._child;
  52053. }
  52054. else {
  52055. this._nextActiveAction = this;
  52056. }
  52057. };
  52058. /**
  52059. * Adds action to chain of actions, may be a DoNothingAction
  52060. * @param action defines the next action to execute
  52061. * @returns The action passed in
  52062. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52063. */
  52064. Action.prototype.then = function (action) {
  52065. this._child = action;
  52066. action._actionManager = this._actionManager;
  52067. action._prepare();
  52068. return action;
  52069. };
  52070. /**
  52071. * Internal only
  52072. * @hidden
  52073. */
  52074. Action.prototype._getProperty = function (propertyPath) {
  52075. return this._actionManager._getProperty(propertyPath);
  52076. };
  52077. /**
  52078. * Internal only
  52079. * @hidden
  52080. */
  52081. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52082. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52083. };
  52084. /**
  52085. * Serialize placeholder for child classes
  52086. * @param parent of child
  52087. * @returns the serialized object
  52088. */
  52089. Action.prototype.serialize = function (parent) {
  52090. };
  52091. /**
  52092. * Internal only called by serialize
  52093. * @hidden
  52094. */
  52095. Action.prototype._serialize = function (serializedAction, parent) {
  52096. var serializationObject = {
  52097. type: 1,
  52098. children: [],
  52099. name: serializedAction.name,
  52100. properties: serializedAction.properties || []
  52101. };
  52102. // Serialize child
  52103. if (this._child) {
  52104. this._child.serialize(serializationObject);
  52105. }
  52106. // Check if "this" has a condition
  52107. if (this._condition) {
  52108. var serializedCondition = this._condition.serialize();
  52109. serializedCondition.children.push(serializationObject);
  52110. if (parent) {
  52111. parent.children.push(serializedCondition);
  52112. }
  52113. return serializedCondition;
  52114. }
  52115. if (parent) {
  52116. parent.children.push(serializationObject);
  52117. }
  52118. return serializationObject;
  52119. };
  52120. /**
  52121. * Internal only
  52122. * @hidden
  52123. */
  52124. Action._SerializeValueAsString = function (value) {
  52125. if (typeof value === "number") {
  52126. return value.toString();
  52127. }
  52128. if (typeof value === "boolean") {
  52129. return value ? "true" : "false";
  52130. }
  52131. if (value instanceof BABYLON.Vector2) {
  52132. return value.x + ", " + value.y;
  52133. }
  52134. if (value instanceof BABYLON.Vector3) {
  52135. return value.x + ", " + value.y + ", " + value.z;
  52136. }
  52137. if (value instanceof BABYLON.Color3) {
  52138. return value.r + ", " + value.g + ", " + value.b;
  52139. }
  52140. if (value instanceof BABYLON.Color4) {
  52141. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52142. }
  52143. return value; // string
  52144. };
  52145. /**
  52146. * Internal only
  52147. * @hidden
  52148. */
  52149. Action._GetTargetProperty = function (target) {
  52150. return {
  52151. name: "target",
  52152. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52153. : target instanceof BABYLON.Light ? "LightProperties"
  52154. : target instanceof BABYLON.Camera ? "CameraProperties"
  52155. : "SceneProperties",
  52156. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52157. };
  52158. };
  52159. return Action;
  52160. }());
  52161. BABYLON.Action = Action;
  52162. })(BABYLON || (BABYLON = {}));
  52163. //# sourceMappingURL=babylon.action.js.map
  52164. var BABYLON;
  52165. (function (BABYLON) {
  52166. /**
  52167. * ActionEvent is the event being sent when an action is triggered.
  52168. */
  52169. var ActionEvent = /** @class */ (function () {
  52170. /**
  52171. * Creates a new ActionEvent
  52172. * @param source The mesh or sprite that triggered the action
  52173. * @param pointerX The X mouse cursor position at the time of the event
  52174. * @param pointerY The Y mouse cursor position at the time of the event
  52175. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52176. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52177. * @param additionalData additional data for the event
  52178. */
  52179. function ActionEvent(
  52180. /** The mesh or sprite that triggered the action */
  52181. source,
  52182. /** The X mouse cursor position at the time of the event */
  52183. pointerX,
  52184. /** The Y mouse cursor position at the time of the event */
  52185. pointerY,
  52186. /** The mesh that is currently pointed at (can be null) */
  52187. meshUnderPointer,
  52188. /** the original (browser) event that triggered the ActionEvent */
  52189. sourceEvent,
  52190. /** additional data for the event */
  52191. additionalData) {
  52192. this.source = source;
  52193. this.pointerX = pointerX;
  52194. this.pointerY = pointerY;
  52195. this.meshUnderPointer = meshUnderPointer;
  52196. this.sourceEvent = sourceEvent;
  52197. this.additionalData = additionalData;
  52198. }
  52199. /**
  52200. * Helper function to auto-create an ActionEvent from a source mesh.
  52201. * @param source The source mesh that triggered the event
  52202. * @param evt The original (browser) event
  52203. * @param additionalData additional data for the event
  52204. * @returns the new ActionEvent
  52205. */
  52206. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52207. var scene = source.getScene();
  52208. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52209. };
  52210. /**
  52211. * Helper function to auto-create an ActionEvent from a source sprite
  52212. * @param source The source sprite that triggered the event
  52213. * @param scene Scene associated with the sprite
  52214. * @param evt The original (browser) event
  52215. * @param additionalData additional data for the event
  52216. * @returns the new ActionEvent
  52217. */
  52218. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52219. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52220. };
  52221. /**
  52222. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52223. * @param scene the scene where the event occurred
  52224. * @param evt The original (browser) event
  52225. * @returns the new ActionEvent
  52226. */
  52227. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52228. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52229. };
  52230. /**
  52231. * Helper function to auto-create an ActionEvent from a primitive
  52232. * @param prim defines the target primitive
  52233. * @param pointerPos defines the pointer position
  52234. * @param evt The original (browser) event
  52235. * @param additionalData additional data for the event
  52236. * @returns the new ActionEvent
  52237. */
  52238. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52239. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52240. };
  52241. return ActionEvent;
  52242. }());
  52243. BABYLON.ActionEvent = ActionEvent;
  52244. /**
  52245. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52246. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52247. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52248. */
  52249. var ActionManager = /** @class */ (function () {
  52250. /**
  52251. * Creates a new action manager
  52252. * @param scene defines the hosting scene
  52253. */
  52254. function ActionManager(scene) {
  52255. // Members
  52256. /** Gets the list of actions */
  52257. this.actions = new Array();
  52258. /** Gets the cursor to use when hovering items */
  52259. this.hoverCursor = '';
  52260. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52261. scene.actionManagers.push(this);
  52262. }
  52263. Object.defineProperty(ActionManager, "NothingTrigger", {
  52264. /**
  52265. * Nothing
  52266. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52267. */
  52268. get: function () {
  52269. return ActionManager._NothingTrigger;
  52270. },
  52271. enumerable: true,
  52272. configurable: true
  52273. });
  52274. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52275. /**
  52276. * On pick
  52277. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52278. */
  52279. get: function () {
  52280. return ActionManager._OnPickTrigger;
  52281. },
  52282. enumerable: true,
  52283. configurable: true
  52284. });
  52285. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52286. /**
  52287. * On left pick
  52288. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52289. */
  52290. get: function () {
  52291. return ActionManager._OnLeftPickTrigger;
  52292. },
  52293. enumerable: true,
  52294. configurable: true
  52295. });
  52296. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52297. /**
  52298. * On right pick
  52299. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52300. */
  52301. get: function () {
  52302. return ActionManager._OnRightPickTrigger;
  52303. },
  52304. enumerable: true,
  52305. configurable: true
  52306. });
  52307. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52308. /**
  52309. * On center pick
  52310. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52311. */
  52312. get: function () {
  52313. return ActionManager._OnCenterPickTrigger;
  52314. },
  52315. enumerable: true,
  52316. configurable: true
  52317. });
  52318. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52319. /**
  52320. * On pick down
  52321. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52322. */
  52323. get: function () {
  52324. return ActionManager._OnPickDownTrigger;
  52325. },
  52326. enumerable: true,
  52327. configurable: true
  52328. });
  52329. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52330. /**
  52331. * On double pick
  52332. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52333. */
  52334. get: function () {
  52335. return ActionManager._OnDoublePickTrigger;
  52336. },
  52337. enumerable: true,
  52338. configurable: true
  52339. });
  52340. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52341. /**
  52342. * On pick up
  52343. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52344. */
  52345. get: function () {
  52346. return ActionManager._OnPickUpTrigger;
  52347. },
  52348. enumerable: true,
  52349. configurable: true
  52350. });
  52351. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52352. /**
  52353. * On pick out.
  52354. * This trigger will only be raised if you also declared a OnPickDown
  52355. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52356. */
  52357. get: function () {
  52358. return ActionManager._OnPickOutTrigger;
  52359. },
  52360. enumerable: true,
  52361. configurable: true
  52362. });
  52363. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52364. /**
  52365. * On long press
  52366. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52367. */
  52368. get: function () {
  52369. return ActionManager._OnLongPressTrigger;
  52370. },
  52371. enumerable: true,
  52372. configurable: true
  52373. });
  52374. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52375. /**
  52376. * On pointer over
  52377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52378. */
  52379. get: function () {
  52380. return ActionManager._OnPointerOverTrigger;
  52381. },
  52382. enumerable: true,
  52383. configurable: true
  52384. });
  52385. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52386. /**
  52387. * On pointer out
  52388. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52389. */
  52390. get: function () {
  52391. return ActionManager._OnPointerOutTrigger;
  52392. },
  52393. enumerable: true,
  52394. configurable: true
  52395. });
  52396. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52397. /**
  52398. * On every frame
  52399. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52400. */
  52401. get: function () {
  52402. return ActionManager._OnEveryFrameTrigger;
  52403. },
  52404. enumerable: true,
  52405. configurable: true
  52406. });
  52407. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52408. /**
  52409. * On intersection enter
  52410. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52411. */
  52412. get: function () {
  52413. return ActionManager._OnIntersectionEnterTrigger;
  52414. },
  52415. enumerable: true,
  52416. configurable: true
  52417. });
  52418. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52419. /**
  52420. * On intersection exit
  52421. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52422. */
  52423. get: function () {
  52424. return ActionManager._OnIntersectionExitTrigger;
  52425. },
  52426. enumerable: true,
  52427. configurable: true
  52428. });
  52429. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52430. /**
  52431. * On key down
  52432. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52433. */
  52434. get: function () {
  52435. return ActionManager._OnKeyDownTrigger;
  52436. },
  52437. enumerable: true,
  52438. configurable: true
  52439. });
  52440. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52441. /**
  52442. * On key up
  52443. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52444. */
  52445. get: function () {
  52446. return ActionManager._OnKeyUpTrigger;
  52447. },
  52448. enumerable: true,
  52449. configurable: true
  52450. });
  52451. // Methods
  52452. /**
  52453. * Releases all associated resources
  52454. */
  52455. ActionManager.prototype.dispose = function () {
  52456. var index = this._scene.actionManagers.indexOf(this);
  52457. for (var i = 0; i < this.actions.length; i++) {
  52458. var action = this.actions[i];
  52459. ActionManager.Triggers[action.trigger]--;
  52460. if (ActionManager.Triggers[action.trigger] === 0) {
  52461. delete ActionManager.Triggers[action.trigger];
  52462. }
  52463. }
  52464. if (index > -1) {
  52465. this._scene.actionManagers.splice(index, 1);
  52466. }
  52467. };
  52468. /**
  52469. * Gets hosting scene
  52470. * @returns the hosting scene
  52471. */
  52472. ActionManager.prototype.getScene = function () {
  52473. return this._scene;
  52474. };
  52475. /**
  52476. * Does this action manager handles actions of any of the given triggers
  52477. * @param triggers defines the triggers to be tested
  52478. * @return a boolean indicating whether one (or more) of the triggers is handled
  52479. */
  52480. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52481. for (var index = 0; index < this.actions.length; index++) {
  52482. var action = this.actions[index];
  52483. if (triggers.indexOf(action.trigger) > -1) {
  52484. return true;
  52485. }
  52486. }
  52487. return false;
  52488. };
  52489. /**
  52490. * Does this action manager handles actions of a given trigger
  52491. * @param trigger defines the trigger to be tested
  52492. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52493. * @return whether the trigger is handled
  52494. */
  52495. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52496. for (var index = 0; index < this.actions.length; index++) {
  52497. var action = this.actions[index];
  52498. if (action.trigger === trigger) {
  52499. if (parameterPredicate) {
  52500. if (parameterPredicate(action.getTriggerParameter())) {
  52501. return true;
  52502. }
  52503. }
  52504. else {
  52505. return true;
  52506. }
  52507. }
  52508. }
  52509. return false;
  52510. };
  52511. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52512. /**
  52513. * Does this action manager has pointer triggers
  52514. */
  52515. get: function () {
  52516. for (var index = 0; index < this.actions.length; index++) {
  52517. var action = this.actions[index];
  52518. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52519. return true;
  52520. }
  52521. }
  52522. return false;
  52523. },
  52524. enumerable: true,
  52525. configurable: true
  52526. });
  52527. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52528. /**
  52529. * Does this action manager has pick triggers
  52530. */
  52531. get: function () {
  52532. for (var index = 0; index < this.actions.length; index++) {
  52533. var action = this.actions[index];
  52534. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52535. return true;
  52536. }
  52537. }
  52538. return false;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. Object.defineProperty(ActionManager, "HasTriggers", {
  52544. /**
  52545. * Does exist one action manager with at least one trigger
  52546. **/
  52547. get: function () {
  52548. for (var t in ActionManager.Triggers) {
  52549. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52550. return true;
  52551. }
  52552. }
  52553. return false;
  52554. },
  52555. enumerable: true,
  52556. configurable: true
  52557. });
  52558. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52559. /**
  52560. * Does exist one action manager with at least one pick trigger
  52561. **/
  52562. get: function () {
  52563. for (var t in ActionManager.Triggers) {
  52564. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52565. var t_int = parseInt(t);
  52566. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52567. return true;
  52568. }
  52569. }
  52570. }
  52571. return false;
  52572. },
  52573. enumerable: true,
  52574. configurable: true
  52575. });
  52576. /**
  52577. * Does exist one action manager that handles actions of a given trigger
  52578. * @param trigger defines the trigger to be tested
  52579. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52580. **/
  52581. ActionManager.HasSpecificTrigger = function (trigger) {
  52582. for (var t in ActionManager.Triggers) {
  52583. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52584. var t_int = parseInt(t);
  52585. if (t_int === trigger) {
  52586. return true;
  52587. }
  52588. }
  52589. }
  52590. return false;
  52591. };
  52592. /**
  52593. * Registers an action to this action manager
  52594. * @param action defines the action to be registered
  52595. * @return the action amended (prepared) after registration
  52596. */
  52597. ActionManager.prototype.registerAction = function (action) {
  52598. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52599. if (this.getScene().actionManager !== this) {
  52600. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52601. return null;
  52602. }
  52603. }
  52604. this.actions.push(action);
  52605. if (ActionManager.Triggers[action.trigger]) {
  52606. ActionManager.Triggers[action.trigger]++;
  52607. }
  52608. else {
  52609. ActionManager.Triggers[action.trigger] = 1;
  52610. }
  52611. action._actionManager = this;
  52612. action._prepare();
  52613. return action;
  52614. };
  52615. /**
  52616. * Unregisters an action to this action manager
  52617. * @param action defines the action to be unregistered
  52618. * @return a boolean indicating whether the action has been unregistered
  52619. */
  52620. ActionManager.prototype.unregisterAction = function (action) {
  52621. var index = this.actions.indexOf(action);
  52622. if (index !== -1) {
  52623. this.actions.splice(index, 1);
  52624. ActionManager.Triggers[action.trigger] -= 1;
  52625. if (ActionManager.Triggers[action.trigger] === 0) {
  52626. delete ActionManager.Triggers[action.trigger];
  52627. }
  52628. delete action._actionManager;
  52629. return true;
  52630. }
  52631. return false;
  52632. };
  52633. /**
  52634. * Process a specific trigger
  52635. * @param trigger defines the trigger to process
  52636. * @param evt defines the event details to be processed
  52637. */
  52638. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52639. for (var index = 0; index < this.actions.length; index++) {
  52640. var action = this.actions[index];
  52641. if (action.trigger === trigger) {
  52642. if (evt) {
  52643. if (trigger === ActionManager.OnKeyUpTrigger
  52644. || trigger === ActionManager.OnKeyDownTrigger) {
  52645. var parameter = action.getTriggerParameter();
  52646. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52647. if (!parameter.toLowerCase) {
  52648. continue;
  52649. }
  52650. var lowerCase = parameter.toLowerCase();
  52651. if (lowerCase !== evt.sourceEvent.key) {
  52652. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52653. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52654. if (actualkey !== lowerCase) {
  52655. continue;
  52656. }
  52657. }
  52658. }
  52659. }
  52660. }
  52661. action._executeCurrent(evt);
  52662. }
  52663. }
  52664. };
  52665. /** @hidden */
  52666. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52667. var properties = propertyPath.split(".");
  52668. for (var index = 0; index < properties.length - 1; index++) {
  52669. target = target[properties[index]];
  52670. }
  52671. return target;
  52672. };
  52673. /** @hidden */
  52674. ActionManager.prototype._getProperty = function (propertyPath) {
  52675. var properties = propertyPath.split(".");
  52676. return properties[properties.length - 1];
  52677. };
  52678. /**
  52679. * Serialize this manager to a JSON object
  52680. * @param name defines the property name to store this manager
  52681. * @returns a JSON representation of this manager
  52682. */
  52683. ActionManager.prototype.serialize = function (name) {
  52684. var root = {
  52685. children: new Array(),
  52686. name: name,
  52687. type: 3,
  52688. properties: new Array() // Empty for root but required
  52689. };
  52690. for (var i = 0; i < this.actions.length; i++) {
  52691. var triggerObject = {
  52692. type: 0,
  52693. children: new Array(),
  52694. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52695. properties: new Array()
  52696. };
  52697. var triggerOptions = this.actions[i].triggerOptions;
  52698. if (triggerOptions && typeof triggerOptions !== "number") {
  52699. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52700. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52701. }
  52702. else {
  52703. var parameter = {};
  52704. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52705. if (triggerOptions.parameter.mesh) {
  52706. parameter._meshId = triggerOptions.parameter.mesh.id;
  52707. }
  52708. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52709. }
  52710. }
  52711. // Serialize child action, recursively
  52712. this.actions[i].serialize(triggerObject);
  52713. // Add serialized trigger
  52714. root.children.push(triggerObject);
  52715. }
  52716. return root;
  52717. };
  52718. /**
  52719. * Creates a new ActionManager from a JSON data
  52720. * @param parsedActions defines the JSON data to read from
  52721. * @param object defines the hosting mesh
  52722. * @param scene defines the hosting scene
  52723. */
  52724. ActionManager.Parse = function (parsedActions, object, scene) {
  52725. var actionManager = new ActionManager(scene);
  52726. if (object === null)
  52727. scene.actionManager = actionManager;
  52728. else
  52729. object.actionManager = actionManager;
  52730. // instanciate a new object
  52731. var instanciate = function (name, params) {
  52732. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52733. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52734. newInstance.constructor.apply(newInstance, params);
  52735. return newInstance;
  52736. };
  52737. var parseParameter = function (name, value, target, propertyPath) {
  52738. if (propertyPath === null) {
  52739. // String, boolean or float
  52740. var floatValue = parseFloat(value);
  52741. if (value === "true" || value === "false")
  52742. return value === "true";
  52743. else
  52744. return isNaN(floatValue) ? value : floatValue;
  52745. }
  52746. var effectiveTarget = propertyPath.split(".");
  52747. var values = value.split(",");
  52748. // Get effective Target
  52749. for (var i = 0; i < effectiveTarget.length; i++) {
  52750. target = target[effectiveTarget[i]];
  52751. }
  52752. // Return appropriate value with its type
  52753. if (typeof (target) === "boolean")
  52754. return values[0] === "true";
  52755. if (typeof (target) === "string")
  52756. return values[0];
  52757. // Parameters with multiple values such as Vector3 etc.
  52758. var split = new Array();
  52759. for (var i = 0; i < values.length; i++)
  52760. split.push(parseFloat(values[i]));
  52761. if (target instanceof BABYLON.Vector3)
  52762. return BABYLON.Vector3.FromArray(split);
  52763. if (target instanceof BABYLON.Vector4)
  52764. return BABYLON.Vector4.FromArray(split);
  52765. if (target instanceof BABYLON.Color3)
  52766. return BABYLON.Color3.FromArray(split);
  52767. if (target instanceof BABYLON.Color4)
  52768. return BABYLON.Color4.FromArray(split);
  52769. return parseFloat(values[0]);
  52770. };
  52771. // traverse graph per trigger
  52772. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52773. if (combineArray === void 0) { combineArray = null; }
  52774. if (parsedAction.detached)
  52775. return;
  52776. var parameters = new Array();
  52777. var target = null;
  52778. var propertyPath = null;
  52779. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52780. // Parameters
  52781. if (parsedAction.type === 2)
  52782. parameters.push(actionManager);
  52783. else
  52784. parameters.push(trigger);
  52785. if (combine) {
  52786. var actions = new Array();
  52787. for (var j = 0; j < parsedAction.combine.length; j++) {
  52788. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52789. }
  52790. parameters.push(actions);
  52791. }
  52792. else {
  52793. for (var i = 0; i < parsedAction.properties.length; i++) {
  52794. var value = parsedAction.properties[i].value;
  52795. var name = parsedAction.properties[i].name;
  52796. var targetType = parsedAction.properties[i].targetType;
  52797. if (name === "target")
  52798. if (targetType !== null && targetType === "SceneProperties")
  52799. value = target = scene;
  52800. else
  52801. value = target = scene.getNodeByName(value);
  52802. else if (name === "parent")
  52803. value = scene.getNodeByName(value);
  52804. else if (name === "sound")
  52805. value = scene.getSoundByName(value);
  52806. else if (name !== "propertyPath") {
  52807. if (parsedAction.type === 2 && name === "operator")
  52808. value = BABYLON.ValueCondition[value];
  52809. else
  52810. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52811. }
  52812. else {
  52813. propertyPath = value;
  52814. }
  52815. parameters.push(value);
  52816. }
  52817. }
  52818. if (combineArray === null) {
  52819. parameters.push(condition);
  52820. }
  52821. else {
  52822. parameters.push(null);
  52823. }
  52824. // If interpolate value action
  52825. if (parsedAction.name === "InterpolateValueAction") {
  52826. var param = parameters[parameters.length - 2];
  52827. parameters[parameters.length - 1] = param;
  52828. parameters[parameters.length - 2] = condition;
  52829. }
  52830. // Action or condition(s) and not CombineAction
  52831. var newAction = instanciate(parsedAction.name, parameters);
  52832. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52833. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52834. if (action)
  52835. action.then(nothing);
  52836. else
  52837. actionManager.registerAction(nothing);
  52838. action = nothing;
  52839. }
  52840. if (combineArray === null) {
  52841. if (newAction instanceof BABYLON.Condition) {
  52842. condition = newAction;
  52843. newAction = action;
  52844. }
  52845. else {
  52846. condition = null;
  52847. if (action)
  52848. action.then(newAction);
  52849. else
  52850. actionManager.registerAction(newAction);
  52851. }
  52852. }
  52853. else {
  52854. combineArray.push(newAction);
  52855. }
  52856. for (var i = 0; i < parsedAction.children.length; i++)
  52857. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52858. };
  52859. // triggers
  52860. for (var i = 0; i < parsedActions.children.length; i++) {
  52861. var triggerParams;
  52862. var trigger = parsedActions.children[i];
  52863. if (trigger.properties.length > 0) {
  52864. var param = trigger.properties[0].value;
  52865. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52866. if (value._meshId) {
  52867. value.mesh = scene.getMeshByID(value._meshId);
  52868. }
  52869. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52870. }
  52871. else
  52872. triggerParams = ActionManager[trigger.name];
  52873. for (var j = 0; j < trigger.children.length; j++) {
  52874. if (!trigger.detached)
  52875. traverse(trigger.children[j], triggerParams, null, null);
  52876. }
  52877. }
  52878. };
  52879. /**
  52880. * Get a trigger name by index
  52881. * @param trigger defines the trigger index
  52882. * @returns a trigger name
  52883. */
  52884. ActionManager.GetTriggerName = function (trigger) {
  52885. switch (trigger) {
  52886. case 0: return "NothingTrigger";
  52887. case 1: return "OnPickTrigger";
  52888. case 2: return "OnLeftPickTrigger";
  52889. case 3: return "OnRightPickTrigger";
  52890. case 4: return "OnCenterPickTrigger";
  52891. case 5: return "OnPickDownTrigger";
  52892. case 6: return "OnPickUpTrigger";
  52893. case 7: return "OnLongPressTrigger";
  52894. case 8: return "OnPointerOverTrigger";
  52895. case 9: return "OnPointerOutTrigger";
  52896. case 10: return "OnEveryFrameTrigger";
  52897. case 11: return "OnIntersectionEnterTrigger";
  52898. case 12: return "OnIntersectionExitTrigger";
  52899. case 13: return "OnKeyDownTrigger";
  52900. case 14: return "OnKeyUpTrigger";
  52901. case 15: return "OnPickOutTrigger";
  52902. default: return "";
  52903. }
  52904. };
  52905. // Statics
  52906. ActionManager._NothingTrigger = 0;
  52907. ActionManager._OnPickTrigger = 1;
  52908. ActionManager._OnLeftPickTrigger = 2;
  52909. ActionManager._OnRightPickTrigger = 3;
  52910. ActionManager._OnCenterPickTrigger = 4;
  52911. ActionManager._OnPickDownTrigger = 5;
  52912. ActionManager._OnDoublePickTrigger = 6;
  52913. ActionManager._OnPickUpTrigger = 7;
  52914. ActionManager._OnLongPressTrigger = 8;
  52915. ActionManager._OnPointerOverTrigger = 9;
  52916. ActionManager._OnPointerOutTrigger = 10;
  52917. ActionManager._OnEveryFrameTrigger = 11;
  52918. ActionManager._OnIntersectionEnterTrigger = 12;
  52919. ActionManager._OnIntersectionExitTrigger = 13;
  52920. ActionManager._OnKeyDownTrigger = 14;
  52921. ActionManager._OnKeyUpTrigger = 15;
  52922. ActionManager._OnPickOutTrigger = 16;
  52923. /** Gets the list of active triggers */
  52924. ActionManager.Triggers = {};
  52925. return ActionManager;
  52926. }());
  52927. BABYLON.ActionManager = ActionManager;
  52928. })(BABYLON || (BABYLON = {}));
  52929. //# sourceMappingURL=babylon.actionManager.js.map
  52930. var BABYLON;
  52931. (function (BABYLON) {
  52932. var InterpolateValueAction = /** @class */ (function (_super) {
  52933. __extends(InterpolateValueAction, _super);
  52934. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52935. if (duration === void 0) { duration = 1000; }
  52936. var _this = _super.call(this, triggerOptions, condition) || this;
  52937. _this.propertyPath = propertyPath;
  52938. _this.value = value;
  52939. _this.duration = duration;
  52940. _this.stopOtherAnimations = stopOtherAnimations;
  52941. _this.onInterpolationDone = onInterpolationDone;
  52942. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52943. _this._target = _this._effectiveTarget = target;
  52944. return _this;
  52945. }
  52946. InterpolateValueAction.prototype._prepare = function () {
  52947. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52948. this._property = this._getProperty(this.propertyPath);
  52949. };
  52950. InterpolateValueAction.prototype.execute = function () {
  52951. var _this = this;
  52952. var scene = this._actionManager.getScene();
  52953. var keys = [
  52954. {
  52955. frame: 0,
  52956. value: this._effectiveTarget[this._property]
  52957. }, {
  52958. frame: 100,
  52959. value: this.value
  52960. }
  52961. ];
  52962. var dataType;
  52963. if (typeof this.value === "number") {
  52964. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  52965. }
  52966. else if (this.value instanceof BABYLON.Color3) {
  52967. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  52968. }
  52969. else if (this.value instanceof BABYLON.Vector3) {
  52970. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  52971. }
  52972. else if (this.value instanceof BABYLON.Matrix) {
  52973. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  52974. }
  52975. else if (this.value instanceof BABYLON.Quaternion) {
  52976. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  52977. }
  52978. else {
  52979. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  52980. return;
  52981. }
  52982. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  52983. animation.setKeys(keys);
  52984. if (this.stopOtherAnimations) {
  52985. scene.stopAnimation(this._effectiveTarget);
  52986. }
  52987. var wrapper = function () {
  52988. _this.onInterpolationDoneObservable.notifyObservers(_this);
  52989. if (_this.onInterpolationDone) {
  52990. _this.onInterpolationDone();
  52991. }
  52992. };
  52993. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  52994. };
  52995. InterpolateValueAction.prototype.serialize = function (parent) {
  52996. return _super.prototype._serialize.call(this, {
  52997. name: "InterpolateValueAction",
  52998. properties: [
  52999. BABYLON.Action._GetTargetProperty(this._target),
  53000. { name: "propertyPath", value: this.propertyPath },
  53001. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53002. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53003. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53004. ]
  53005. }, parent);
  53006. };
  53007. return InterpolateValueAction;
  53008. }(BABYLON.Action));
  53009. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53010. })(BABYLON || (BABYLON = {}));
  53011. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53012. var BABYLON;
  53013. (function (BABYLON) {
  53014. var SwitchBooleanAction = /** @class */ (function (_super) {
  53015. __extends(SwitchBooleanAction, _super);
  53016. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53017. var _this = _super.call(this, triggerOptions, condition) || this;
  53018. _this.propertyPath = propertyPath;
  53019. _this._target = _this._effectiveTarget = target;
  53020. return _this;
  53021. }
  53022. SwitchBooleanAction.prototype._prepare = function () {
  53023. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53024. this._property = this._getProperty(this.propertyPath);
  53025. };
  53026. SwitchBooleanAction.prototype.execute = function () {
  53027. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53028. };
  53029. SwitchBooleanAction.prototype.serialize = function (parent) {
  53030. return _super.prototype._serialize.call(this, {
  53031. name: "SwitchBooleanAction",
  53032. properties: [
  53033. BABYLON.Action._GetTargetProperty(this._target),
  53034. { name: "propertyPath", value: this.propertyPath }
  53035. ]
  53036. }, parent);
  53037. };
  53038. return SwitchBooleanAction;
  53039. }(BABYLON.Action));
  53040. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53041. var SetStateAction = /** @class */ (function (_super) {
  53042. __extends(SetStateAction, _super);
  53043. function SetStateAction(triggerOptions, target, value, condition) {
  53044. var _this = _super.call(this, triggerOptions, condition) || this;
  53045. _this.value = value;
  53046. _this._target = target;
  53047. return _this;
  53048. }
  53049. SetStateAction.prototype.execute = function () {
  53050. this._target.state = this.value;
  53051. };
  53052. SetStateAction.prototype.serialize = function (parent) {
  53053. return _super.prototype._serialize.call(this, {
  53054. name: "SetStateAction",
  53055. properties: [
  53056. BABYLON.Action._GetTargetProperty(this._target),
  53057. { name: "value", value: this.value }
  53058. ]
  53059. }, parent);
  53060. };
  53061. return SetStateAction;
  53062. }(BABYLON.Action));
  53063. BABYLON.SetStateAction = SetStateAction;
  53064. var SetValueAction = /** @class */ (function (_super) {
  53065. __extends(SetValueAction, _super);
  53066. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53067. var _this = _super.call(this, triggerOptions, condition) || this;
  53068. _this.propertyPath = propertyPath;
  53069. _this.value = value;
  53070. _this._target = _this._effectiveTarget = target;
  53071. return _this;
  53072. }
  53073. SetValueAction.prototype._prepare = function () {
  53074. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53075. this._property = this._getProperty(this.propertyPath);
  53076. };
  53077. SetValueAction.prototype.execute = function () {
  53078. this._effectiveTarget[this._property] = this.value;
  53079. if (this._target.markAsDirty) {
  53080. this._target.markAsDirty(this._property);
  53081. }
  53082. };
  53083. SetValueAction.prototype.serialize = function (parent) {
  53084. return _super.prototype._serialize.call(this, {
  53085. name: "SetValueAction",
  53086. properties: [
  53087. BABYLON.Action._GetTargetProperty(this._target),
  53088. { name: "propertyPath", value: this.propertyPath },
  53089. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53090. ]
  53091. }, parent);
  53092. };
  53093. return SetValueAction;
  53094. }(BABYLON.Action));
  53095. BABYLON.SetValueAction = SetValueAction;
  53096. var IncrementValueAction = /** @class */ (function (_super) {
  53097. __extends(IncrementValueAction, _super);
  53098. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53099. var _this = _super.call(this, triggerOptions, condition) || this;
  53100. _this.propertyPath = propertyPath;
  53101. _this.value = value;
  53102. _this._target = _this._effectiveTarget = target;
  53103. return _this;
  53104. }
  53105. IncrementValueAction.prototype._prepare = function () {
  53106. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53107. this._property = this._getProperty(this.propertyPath);
  53108. if (typeof this._effectiveTarget[this._property] !== "number") {
  53109. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53110. }
  53111. };
  53112. IncrementValueAction.prototype.execute = function () {
  53113. this._effectiveTarget[this._property] += this.value;
  53114. if (this._target.markAsDirty) {
  53115. this._target.markAsDirty(this._property);
  53116. }
  53117. };
  53118. IncrementValueAction.prototype.serialize = function (parent) {
  53119. return _super.prototype._serialize.call(this, {
  53120. name: "IncrementValueAction",
  53121. properties: [
  53122. BABYLON.Action._GetTargetProperty(this._target),
  53123. { name: "propertyPath", value: this.propertyPath },
  53124. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53125. ]
  53126. }, parent);
  53127. };
  53128. return IncrementValueAction;
  53129. }(BABYLON.Action));
  53130. BABYLON.IncrementValueAction = IncrementValueAction;
  53131. var PlayAnimationAction = /** @class */ (function (_super) {
  53132. __extends(PlayAnimationAction, _super);
  53133. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53134. var _this = _super.call(this, triggerOptions, condition) || this;
  53135. _this.from = from;
  53136. _this.to = to;
  53137. _this.loop = loop;
  53138. _this._target = target;
  53139. return _this;
  53140. }
  53141. PlayAnimationAction.prototype._prepare = function () {
  53142. };
  53143. PlayAnimationAction.prototype.execute = function () {
  53144. var scene = this._actionManager.getScene();
  53145. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53146. };
  53147. PlayAnimationAction.prototype.serialize = function (parent) {
  53148. return _super.prototype._serialize.call(this, {
  53149. name: "PlayAnimationAction",
  53150. properties: [
  53151. BABYLON.Action._GetTargetProperty(this._target),
  53152. { name: "from", value: String(this.from) },
  53153. { name: "to", value: String(this.to) },
  53154. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53155. ]
  53156. }, parent);
  53157. };
  53158. return PlayAnimationAction;
  53159. }(BABYLON.Action));
  53160. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53161. var StopAnimationAction = /** @class */ (function (_super) {
  53162. __extends(StopAnimationAction, _super);
  53163. function StopAnimationAction(triggerOptions, target, condition) {
  53164. var _this = _super.call(this, triggerOptions, condition) || this;
  53165. _this._target = target;
  53166. return _this;
  53167. }
  53168. StopAnimationAction.prototype._prepare = function () {
  53169. };
  53170. StopAnimationAction.prototype.execute = function () {
  53171. var scene = this._actionManager.getScene();
  53172. scene.stopAnimation(this._target);
  53173. };
  53174. StopAnimationAction.prototype.serialize = function (parent) {
  53175. return _super.prototype._serialize.call(this, {
  53176. name: "StopAnimationAction",
  53177. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53178. }, parent);
  53179. };
  53180. return StopAnimationAction;
  53181. }(BABYLON.Action));
  53182. BABYLON.StopAnimationAction = StopAnimationAction;
  53183. var DoNothingAction = /** @class */ (function (_super) {
  53184. __extends(DoNothingAction, _super);
  53185. function DoNothingAction(triggerOptions, condition) {
  53186. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53187. return _super.call(this, triggerOptions, condition) || this;
  53188. }
  53189. DoNothingAction.prototype.execute = function () {
  53190. };
  53191. DoNothingAction.prototype.serialize = function (parent) {
  53192. return _super.prototype._serialize.call(this, {
  53193. name: "DoNothingAction",
  53194. properties: []
  53195. }, parent);
  53196. };
  53197. return DoNothingAction;
  53198. }(BABYLON.Action));
  53199. BABYLON.DoNothingAction = DoNothingAction;
  53200. var CombineAction = /** @class */ (function (_super) {
  53201. __extends(CombineAction, _super);
  53202. function CombineAction(triggerOptions, children, condition) {
  53203. var _this = _super.call(this, triggerOptions, condition) || this;
  53204. _this.children = children;
  53205. return _this;
  53206. }
  53207. CombineAction.prototype._prepare = function () {
  53208. for (var index = 0; index < this.children.length; index++) {
  53209. this.children[index]._actionManager = this._actionManager;
  53210. this.children[index]._prepare();
  53211. }
  53212. };
  53213. CombineAction.prototype.execute = function (evt) {
  53214. for (var index = 0; index < this.children.length; index++) {
  53215. this.children[index].execute(evt);
  53216. }
  53217. };
  53218. CombineAction.prototype.serialize = function (parent) {
  53219. var serializationObject = _super.prototype._serialize.call(this, {
  53220. name: "CombineAction",
  53221. properties: [],
  53222. combine: []
  53223. }, parent);
  53224. for (var i = 0; i < this.children.length; i++) {
  53225. serializationObject.combine.push(this.children[i].serialize(null));
  53226. }
  53227. return serializationObject;
  53228. };
  53229. return CombineAction;
  53230. }(BABYLON.Action));
  53231. BABYLON.CombineAction = CombineAction;
  53232. var ExecuteCodeAction = /** @class */ (function (_super) {
  53233. __extends(ExecuteCodeAction, _super);
  53234. function ExecuteCodeAction(triggerOptions, func, condition) {
  53235. var _this = _super.call(this, triggerOptions, condition) || this;
  53236. _this.func = func;
  53237. return _this;
  53238. }
  53239. ExecuteCodeAction.prototype.execute = function (evt) {
  53240. this.func(evt);
  53241. };
  53242. return ExecuteCodeAction;
  53243. }(BABYLON.Action));
  53244. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53245. var SetParentAction = /** @class */ (function (_super) {
  53246. __extends(SetParentAction, _super);
  53247. function SetParentAction(triggerOptions, target, parent, condition) {
  53248. var _this = _super.call(this, triggerOptions, condition) || this;
  53249. _this._target = target;
  53250. _this._parent = parent;
  53251. return _this;
  53252. }
  53253. SetParentAction.prototype._prepare = function () {
  53254. };
  53255. SetParentAction.prototype.execute = function () {
  53256. if (this._target.parent === this._parent) {
  53257. return;
  53258. }
  53259. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53260. invertParentWorldMatrix.invert();
  53261. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53262. this._target.parent = this._parent;
  53263. };
  53264. SetParentAction.prototype.serialize = function (parent) {
  53265. return _super.prototype._serialize.call(this, {
  53266. name: "SetParentAction",
  53267. properties: [
  53268. BABYLON.Action._GetTargetProperty(this._target),
  53269. BABYLON.Action._GetTargetProperty(this._parent),
  53270. ]
  53271. }, parent);
  53272. };
  53273. return SetParentAction;
  53274. }(BABYLON.Action));
  53275. BABYLON.SetParentAction = SetParentAction;
  53276. var PlaySoundAction = /** @class */ (function (_super) {
  53277. __extends(PlaySoundAction, _super);
  53278. function PlaySoundAction(triggerOptions, sound, condition) {
  53279. var _this = _super.call(this, triggerOptions, condition) || this;
  53280. _this._sound = sound;
  53281. return _this;
  53282. }
  53283. PlaySoundAction.prototype._prepare = function () {
  53284. };
  53285. PlaySoundAction.prototype.execute = function () {
  53286. if (this._sound !== undefined)
  53287. this._sound.play();
  53288. };
  53289. PlaySoundAction.prototype.serialize = function (parent) {
  53290. return _super.prototype._serialize.call(this, {
  53291. name: "PlaySoundAction",
  53292. properties: [{ name: "sound", value: this._sound.name }]
  53293. }, parent);
  53294. };
  53295. return PlaySoundAction;
  53296. }(BABYLON.Action));
  53297. BABYLON.PlaySoundAction = PlaySoundAction;
  53298. var StopSoundAction = /** @class */ (function (_super) {
  53299. __extends(StopSoundAction, _super);
  53300. function StopSoundAction(triggerOptions, sound, condition) {
  53301. var _this = _super.call(this, triggerOptions, condition) || this;
  53302. _this._sound = sound;
  53303. return _this;
  53304. }
  53305. StopSoundAction.prototype._prepare = function () {
  53306. };
  53307. StopSoundAction.prototype.execute = function () {
  53308. if (this._sound !== undefined)
  53309. this._sound.stop();
  53310. };
  53311. StopSoundAction.prototype.serialize = function (parent) {
  53312. return _super.prototype._serialize.call(this, {
  53313. name: "StopSoundAction",
  53314. properties: [{ name: "sound", value: this._sound.name }]
  53315. }, parent);
  53316. };
  53317. return StopSoundAction;
  53318. }(BABYLON.Action));
  53319. BABYLON.StopSoundAction = StopSoundAction;
  53320. })(BABYLON || (BABYLON = {}));
  53321. //# sourceMappingURL=babylon.directActions.js.map
  53322. var BABYLON;
  53323. (function (BABYLON) {
  53324. var SpriteManager = /** @class */ (function () {
  53325. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53326. if (epsilon === void 0) { epsilon = 0.01; }
  53327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53328. this.name = name;
  53329. this.sprites = new Array();
  53330. this.renderingGroupId = 0;
  53331. this.layerMask = 0x0FFFFFFF;
  53332. this.fogEnabled = true;
  53333. this.isPickable = false;
  53334. /**
  53335. * An event triggered when the manager is disposed.
  53336. */
  53337. this.onDisposeObservable = new BABYLON.Observable();
  53338. this._vertexBuffers = {};
  53339. this._capacity = capacity;
  53340. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53341. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53342. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53343. if (cellSize.width && cellSize.height) {
  53344. this.cellWidth = cellSize.width;
  53345. this.cellHeight = cellSize.height;
  53346. }
  53347. else if (cellSize !== undefined) {
  53348. this.cellWidth = cellSize;
  53349. this.cellHeight = cellSize;
  53350. }
  53351. else {
  53352. return;
  53353. }
  53354. this._epsilon = epsilon;
  53355. this._scene = scene;
  53356. this._scene.spriteManagers.push(this);
  53357. var indices = [];
  53358. var index = 0;
  53359. for (var count = 0; count < capacity; count++) {
  53360. indices.push(index);
  53361. indices.push(index + 1);
  53362. indices.push(index + 2);
  53363. indices.push(index);
  53364. indices.push(index + 2);
  53365. indices.push(index + 3);
  53366. index += 4;
  53367. }
  53368. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53369. // VBO
  53370. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53371. this._vertexData = new Float32Array(capacity * 16 * 4);
  53372. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53373. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53374. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53375. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53376. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53377. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53378. this._vertexBuffers["options"] = options;
  53379. this._vertexBuffers["cellInfo"] = cellInfo;
  53380. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53381. // Effects
  53382. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53383. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53384. }
  53385. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53386. set: function (callback) {
  53387. if (this._onDisposeObserver) {
  53388. this.onDisposeObservable.remove(this._onDisposeObserver);
  53389. }
  53390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53391. },
  53392. enumerable: true,
  53393. configurable: true
  53394. });
  53395. Object.defineProperty(SpriteManager.prototype, "texture", {
  53396. get: function () {
  53397. return this._spriteTexture;
  53398. },
  53399. set: function (value) {
  53400. this._spriteTexture = value;
  53401. },
  53402. enumerable: true,
  53403. configurable: true
  53404. });
  53405. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53406. var arrayOffset = index * 16;
  53407. if (offsetX === 0)
  53408. offsetX = this._epsilon;
  53409. else if (offsetX === 1)
  53410. offsetX = 1 - this._epsilon;
  53411. if (offsetY === 0)
  53412. offsetY = this._epsilon;
  53413. else if (offsetY === 1)
  53414. offsetY = 1 - this._epsilon;
  53415. this._vertexData[arrayOffset] = sprite.position.x;
  53416. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53417. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53418. this._vertexData[arrayOffset + 3] = sprite.angle;
  53419. this._vertexData[arrayOffset + 4] = sprite.width;
  53420. this._vertexData[arrayOffset + 5] = sprite.height;
  53421. this._vertexData[arrayOffset + 6] = offsetX;
  53422. this._vertexData[arrayOffset + 7] = offsetY;
  53423. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53424. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53425. var offset = (sprite.cellIndex / rowSize) >> 0;
  53426. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53427. this._vertexData[arrayOffset + 11] = offset;
  53428. // Color
  53429. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53430. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53431. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53432. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53433. };
  53434. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53435. var count = Math.min(this._capacity, this.sprites.length);
  53436. var min = BABYLON.Vector3.Zero();
  53437. var max = BABYLON.Vector3.Zero();
  53438. var distance = Number.MAX_VALUE;
  53439. var currentSprite = null;
  53440. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53441. var cameraView = camera.getViewMatrix();
  53442. for (var index = 0; index < count; index++) {
  53443. var sprite = this.sprites[index];
  53444. if (!sprite) {
  53445. continue;
  53446. }
  53447. if (predicate) {
  53448. if (!predicate(sprite)) {
  53449. continue;
  53450. }
  53451. }
  53452. else if (!sprite.isPickable) {
  53453. continue;
  53454. }
  53455. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53456. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53457. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53458. if (ray.intersectsBoxMinMax(min, max)) {
  53459. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53460. if (distance > currentDistance) {
  53461. distance = currentDistance;
  53462. currentSprite = sprite;
  53463. if (fastCheck) {
  53464. break;
  53465. }
  53466. }
  53467. }
  53468. }
  53469. if (currentSprite) {
  53470. var result = new BABYLON.PickingInfo();
  53471. result.hit = true;
  53472. result.pickedSprite = currentSprite;
  53473. result.distance = distance;
  53474. return result;
  53475. }
  53476. return null;
  53477. };
  53478. SpriteManager.prototype.render = function () {
  53479. // Check
  53480. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53481. return;
  53482. var engine = this._scene.getEngine();
  53483. var baseSize = this._spriteTexture.getBaseSize();
  53484. // Sprites
  53485. var deltaTime = engine.getDeltaTime();
  53486. var max = Math.min(this._capacity, this.sprites.length);
  53487. var rowSize = baseSize.width / this.cellWidth;
  53488. var offset = 0;
  53489. for (var index = 0; index < max; index++) {
  53490. var sprite = this.sprites[index];
  53491. if (!sprite || !sprite.isVisible) {
  53492. continue;
  53493. }
  53494. sprite._animate(deltaTime);
  53495. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53496. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53497. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53498. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53499. }
  53500. this._buffer.update(this._vertexData);
  53501. // Render
  53502. var effect = this._effectBase;
  53503. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53504. effect = this._effectFog;
  53505. }
  53506. engine.enableEffect(effect);
  53507. var viewMatrix = this._scene.getViewMatrix();
  53508. effect.setTexture("diffuseSampler", this._spriteTexture);
  53509. effect.setMatrix("view", viewMatrix);
  53510. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53511. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53512. // Fog
  53513. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53514. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53515. effect.setColor3("vFogColor", this._scene.fogColor);
  53516. }
  53517. // VBOs
  53518. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53519. // Draw order
  53520. engine.setDepthFunctionToLessOrEqual();
  53521. effect.setBool("alphaTest", true);
  53522. engine.setColorWrite(false);
  53523. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53524. engine.setColorWrite(true);
  53525. effect.setBool("alphaTest", false);
  53526. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53527. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53529. };
  53530. SpriteManager.prototype.dispose = function () {
  53531. if (this._buffer) {
  53532. this._buffer.dispose();
  53533. this._buffer = null;
  53534. }
  53535. if (this._indexBuffer) {
  53536. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53537. this._indexBuffer = null;
  53538. }
  53539. if (this._spriteTexture) {
  53540. this._spriteTexture.dispose();
  53541. this._spriteTexture = null;
  53542. }
  53543. // Remove from scene
  53544. var index = this._scene.spriteManagers.indexOf(this);
  53545. this._scene.spriteManagers.splice(index, 1);
  53546. // Callback
  53547. this.onDisposeObservable.notifyObservers(this);
  53548. this.onDisposeObservable.clear();
  53549. };
  53550. return SpriteManager;
  53551. }());
  53552. BABYLON.SpriteManager = SpriteManager;
  53553. })(BABYLON || (BABYLON = {}));
  53554. //# sourceMappingURL=babylon.spriteManager.js.map
  53555. var BABYLON;
  53556. (function (BABYLON) {
  53557. var Sprite = /** @class */ (function () {
  53558. function Sprite(name, manager) {
  53559. this.name = name;
  53560. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53561. this.width = 1.0;
  53562. this.height = 1.0;
  53563. this.angle = 0;
  53564. this.cellIndex = 0;
  53565. this.invertU = 0;
  53566. this.invertV = 0;
  53567. this.animations = new Array();
  53568. this.isPickable = false;
  53569. this._animationStarted = false;
  53570. this._loopAnimation = false;
  53571. this._fromIndex = 0;
  53572. this._toIndex = 0;
  53573. this._delay = 0;
  53574. this._direction = 1;
  53575. this._time = 0;
  53576. /**
  53577. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53578. */
  53579. this.isVisible = true;
  53580. this._manager = manager;
  53581. this._manager.sprites.push(this);
  53582. this.position = BABYLON.Vector3.Zero();
  53583. }
  53584. Object.defineProperty(Sprite.prototype, "size", {
  53585. get: function () {
  53586. return this.width;
  53587. },
  53588. set: function (value) {
  53589. this.width = value;
  53590. this.height = value;
  53591. },
  53592. enumerable: true,
  53593. configurable: true
  53594. });
  53595. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53596. this._fromIndex = from;
  53597. this._toIndex = to;
  53598. this._loopAnimation = loop;
  53599. this._delay = delay;
  53600. this._animationStarted = true;
  53601. this._direction = from < to ? 1 : -1;
  53602. this.cellIndex = from;
  53603. this._time = 0;
  53604. this._onAnimationEnd = onAnimationEnd;
  53605. };
  53606. Sprite.prototype.stopAnimation = function () {
  53607. this._animationStarted = false;
  53608. };
  53609. Sprite.prototype._animate = function (deltaTime) {
  53610. if (!this._animationStarted)
  53611. return;
  53612. this._time += deltaTime;
  53613. if (this._time > this._delay) {
  53614. this._time = this._time % this._delay;
  53615. this.cellIndex += this._direction;
  53616. if (this.cellIndex > this._toIndex) {
  53617. if (this._loopAnimation) {
  53618. this.cellIndex = this._fromIndex;
  53619. }
  53620. else {
  53621. this.cellIndex = this._toIndex;
  53622. this._animationStarted = false;
  53623. if (this._onAnimationEnd) {
  53624. this._onAnimationEnd();
  53625. }
  53626. if (this.disposeWhenFinishedAnimating) {
  53627. this.dispose();
  53628. }
  53629. }
  53630. }
  53631. }
  53632. };
  53633. Sprite.prototype.dispose = function () {
  53634. for (var i = 0; i < this._manager.sprites.length; i++) {
  53635. if (this._manager.sprites[i] == this) {
  53636. this._manager.sprites.splice(i, 1);
  53637. }
  53638. }
  53639. };
  53640. return Sprite;
  53641. }());
  53642. BABYLON.Sprite = Sprite;
  53643. })(BABYLON || (BABYLON = {}));
  53644. //# sourceMappingURL=babylon.sprite.js.map
  53645. var BABYLON;
  53646. (function (BABYLON) {
  53647. var IntersectionInfo = /** @class */ (function () {
  53648. function IntersectionInfo(bu, bv, distance) {
  53649. this.bu = bu;
  53650. this.bv = bv;
  53651. this.distance = distance;
  53652. this.faceId = 0;
  53653. this.subMeshId = 0;
  53654. }
  53655. return IntersectionInfo;
  53656. }());
  53657. BABYLON.IntersectionInfo = IntersectionInfo;
  53658. /**
  53659. * Information about the result of picking within a scene
  53660. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53661. */
  53662. var PickingInfo = /** @class */ (function () {
  53663. function PickingInfo() {
  53664. /**
  53665. * If the pick collided with an object
  53666. */
  53667. this.hit = false;
  53668. /**
  53669. * Distance away where the pick collided
  53670. */
  53671. this.distance = 0;
  53672. /**
  53673. * The location of pick collision
  53674. */
  53675. this.pickedPoint = null;
  53676. /**
  53677. * The mesh corrisponding the the pick collision
  53678. */
  53679. this.pickedMesh = null;
  53680. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53681. this.bu = 0;
  53682. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53683. this.bv = 0;
  53684. /** The id of the face on the mesh that was picked */
  53685. this.faceId = -1;
  53686. /** Id of the the submesh that was picked */
  53687. this.subMeshId = 0;
  53688. /** If a sprite was picked, this will be the sprite the pick collided with */
  53689. this.pickedSprite = null;
  53690. /**
  53691. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53692. */
  53693. this.originMesh = null;
  53694. /**
  53695. * The ray that was used to perform the picking.
  53696. */
  53697. this.ray = null;
  53698. }
  53699. /**
  53700. * Gets the normal corrispodning to the face the pick collided with
  53701. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53702. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53703. * @returns The normal corrispodning to the face the pick collided with
  53704. */
  53705. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53706. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53707. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53708. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53709. return null;
  53710. }
  53711. var indices = this.pickedMesh.getIndices();
  53712. if (!indices) {
  53713. return null;
  53714. }
  53715. var result;
  53716. if (useVerticesNormals) {
  53717. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53718. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53719. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53720. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53721. normal0 = normal0.scale(this.bu);
  53722. normal1 = normal1.scale(this.bv);
  53723. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53724. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53725. }
  53726. else {
  53727. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53728. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53729. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53730. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53731. var p1p2 = vertex1.subtract(vertex2);
  53732. var p3p2 = vertex3.subtract(vertex2);
  53733. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53734. }
  53735. if (useWorldCoordinates) {
  53736. var wm = this.pickedMesh.getWorldMatrix();
  53737. if (this.pickedMesh.nonUniformScaling) {
  53738. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53739. wm = BABYLON.Tmp.Matrix[0];
  53740. wm.setTranslationFromFloats(0, 0, 0);
  53741. wm.invert();
  53742. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53743. wm = BABYLON.Tmp.Matrix[1];
  53744. }
  53745. result = BABYLON.Vector3.TransformNormal(result, wm);
  53746. }
  53747. result.normalize();
  53748. return result;
  53749. };
  53750. /**
  53751. * Gets the texture coordinates of where the pick occured
  53752. * @returns the vector containing the coordnates of the texture
  53753. */
  53754. PickingInfo.prototype.getTextureCoordinates = function () {
  53755. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53756. return null;
  53757. }
  53758. var indices = this.pickedMesh.getIndices();
  53759. if (!indices) {
  53760. return null;
  53761. }
  53762. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53763. if (!uvs) {
  53764. return null;
  53765. }
  53766. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53767. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53768. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53769. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53770. uv1 = uv1.scale(this.bu);
  53771. uv2 = uv2.scale(this.bv);
  53772. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53773. };
  53774. return PickingInfo;
  53775. }());
  53776. BABYLON.PickingInfo = PickingInfo;
  53777. })(BABYLON || (BABYLON = {}));
  53778. //# sourceMappingURL=babylon.pickingInfo.js.map
  53779. var BABYLON;
  53780. (function (BABYLON) {
  53781. var Ray = /** @class */ (function () {
  53782. function Ray(origin, direction, length) {
  53783. if (length === void 0) { length = Number.MAX_VALUE; }
  53784. this.origin = origin;
  53785. this.direction = direction;
  53786. this.length = length;
  53787. }
  53788. // Methods
  53789. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53790. var d = 0.0;
  53791. var maxValue = Number.MAX_VALUE;
  53792. var inv;
  53793. var min;
  53794. var max;
  53795. var temp;
  53796. if (Math.abs(this.direction.x) < 0.0000001) {
  53797. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53798. return false;
  53799. }
  53800. }
  53801. else {
  53802. inv = 1.0 / this.direction.x;
  53803. min = (minimum.x - this.origin.x) * inv;
  53804. max = (maximum.x - this.origin.x) * inv;
  53805. if (max === -Infinity) {
  53806. max = Infinity;
  53807. }
  53808. if (min > max) {
  53809. temp = min;
  53810. min = max;
  53811. max = temp;
  53812. }
  53813. d = Math.max(min, d);
  53814. maxValue = Math.min(max, maxValue);
  53815. if (d > maxValue) {
  53816. return false;
  53817. }
  53818. }
  53819. if (Math.abs(this.direction.y) < 0.0000001) {
  53820. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53821. return false;
  53822. }
  53823. }
  53824. else {
  53825. inv = 1.0 / this.direction.y;
  53826. min = (minimum.y - this.origin.y) * inv;
  53827. max = (maximum.y - this.origin.y) * inv;
  53828. if (max === -Infinity) {
  53829. max = Infinity;
  53830. }
  53831. if (min > max) {
  53832. temp = min;
  53833. min = max;
  53834. max = temp;
  53835. }
  53836. d = Math.max(min, d);
  53837. maxValue = Math.min(max, maxValue);
  53838. if (d > maxValue) {
  53839. return false;
  53840. }
  53841. }
  53842. if (Math.abs(this.direction.z) < 0.0000001) {
  53843. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53844. return false;
  53845. }
  53846. }
  53847. else {
  53848. inv = 1.0 / this.direction.z;
  53849. min = (minimum.z - this.origin.z) * inv;
  53850. max = (maximum.z - this.origin.z) * inv;
  53851. if (max === -Infinity) {
  53852. max = Infinity;
  53853. }
  53854. if (min > max) {
  53855. temp = min;
  53856. min = max;
  53857. max = temp;
  53858. }
  53859. d = Math.max(min, d);
  53860. maxValue = Math.min(max, maxValue);
  53861. if (d > maxValue) {
  53862. return false;
  53863. }
  53864. }
  53865. return true;
  53866. };
  53867. Ray.prototype.intersectsBox = function (box) {
  53868. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53869. };
  53870. Ray.prototype.intersectsSphere = function (sphere) {
  53871. var x = sphere.center.x - this.origin.x;
  53872. var y = sphere.center.y - this.origin.y;
  53873. var z = sphere.center.z - this.origin.z;
  53874. var pyth = (x * x) + (y * y) + (z * z);
  53875. var rr = sphere.radius * sphere.radius;
  53876. if (pyth <= rr) {
  53877. return true;
  53878. }
  53879. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53880. if (dot < 0.0) {
  53881. return false;
  53882. }
  53883. var temp = pyth - (dot * dot);
  53884. return temp <= rr;
  53885. };
  53886. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53887. if (!this._edge1) {
  53888. this._edge1 = BABYLON.Vector3.Zero();
  53889. this._edge2 = BABYLON.Vector3.Zero();
  53890. this._pvec = BABYLON.Vector3.Zero();
  53891. this._tvec = BABYLON.Vector3.Zero();
  53892. this._qvec = BABYLON.Vector3.Zero();
  53893. }
  53894. vertex1.subtractToRef(vertex0, this._edge1);
  53895. vertex2.subtractToRef(vertex0, this._edge2);
  53896. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53897. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53898. if (det === 0) {
  53899. return null;
  53900. }
  53901. var invdet = 1 / det;
  53902. this.origin.subtractToRef(vertex0, this._tvec);
  53903. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53904. if (bu < 0 || bu > 1.0) {
  53905. return null;
  53906. }
  53907. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53908. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53909. if (bv < 0 || bu + bv > 1.0) {
  53910. return null;
  53911. }
  53912. //check if the distance is longer than the predefined length.
  53913. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53914. if (distance > this.length) {
  53915. return null;
  53916. }
  53917. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53918. };
  53919. Ray.prototype.intersectsPlane = function (plane) {
  53920. var distance;
  53921. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53922. if (Math.abs(result1) < 9.99999997475243E-07) {
  53923. return null;
  53924. }
  53925. else {
  53926. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53927. distance = (-plane.d - result2) / result1;
  53928. if (distance < 0.0) {
  53929. if (distance < -9.99999997475243E-07) {
  53930. return null;
  53931. }
  53932. else {
  53933. return 0;
  53934. }
  53935. }
  53936. return distance;
  53937. }
  53938. };
  53939. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53940. var tm = BABYLON.Tmp.Matrix[0];
  53941. mesh.getWorldMatrix().invertToRef(tm);
  53942. if (this._tmpRay) {
  53943. Ray.TransformToRef(this, tm, this._tmpRay);
  53944. }
  53945. else {
  53946. this._tmpRay = Ray.Transform(this, tm);
  53947. }
  53948. return mesh.intersects(this._tmpRay, fastCheck);
  53949. };
  53950. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53951. if (results) {
  53952. results.length = 0;
  53953. }
  53954. else {
  53955. results = [];
  53956. }
  53957. for (var i = 0; i < meshes.length; i++) {
  53958. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53959. if (pickInfo.hit) {
  53960. results.push(pickInfo);
  53961. }
  53962. }
  53963. results.sort(this._comparePickingInfo);
  53964. return results;
  53965. };
  53966. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53967. if (pickingInfoA.distance < pickingInfoB.distance) {
  53968. return -1;
  53969. }
  53970. else if (pickingInfoA.distance > pickingInfoB.distance) {
  53971. return 1;
  53972. }
  53973. else {
  53974. return 0;
  53975. }
  53976. };
  53977. /**
  53978. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  53979. * @param sega the first point of the segment to test the intersection against
  53980. * @param segb the second point of the segment to test the intersection against
  53981. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  53982. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  53983. */
  53984. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  53985. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  53986. var u = segb.subtract(sega);
  53987. var v = rsegb.subtract(this.origin);
  53988. var w = sega.subtract(this.origin);
  53989. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  53990. var b = BABYLON.Vector3.Dot(u, v);
  53991. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  53992. var d = BABYLON.Vector3.Dot(u, w);
  53993. var e = BABYLON.Vector3.Dot(v, w);
  53994. var D = a * c - b * b; // always >= 0
  53995. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  53996. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  53997. // compute the line parameters of the two closest points
  53998. if (D < Ray.smallnum) { // the lines are almost parallel
  53999. sN = 0.0; // force using point P0 on segment S1
  54000. sD = 1.0; // to prevent possible division by 0.0 later
  54001. tN = e;
  54002. tD = c;
  54003. }
  54004. else { // get the closest points on the infinite lines
  54005. sN = (b * e - c * d);
  54006. tN = (a * e - b * d);
  54007. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54008. sN = 0.0;
  54009. tN = e;
  54010. tD = c;
  54011. }
  54012. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54013. sN = sD;
  54014. tN = e + b;
  54015. tD = c;
  54016. }
  54017. }
  54018. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54019. tN = 0.0;
  54020. // recompute sc for this edge
  54021. if (-d < 0.0) {
  54022. sN = 0.0;
  54023. }
  54024. else if (-d > a)
  54025. sN = sD;
  54026. else {
  54027. sN = -d;
  54028. sD = a;
  54029. }
  54030. }
  54031. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54032. tN = tD;
  54033. // recompute sc for this edge
  54034. if ((-d + b) < 0.0) {
  54035. sN = 0;
  54036. }
  54037. else if ((-d + b) > a) {
  54038. sN = sD;
  54039. }
  54040. else {
  54041. sN = (-d + b);
  54042. sD = a;
  54043. }
  54044. }
  54045. // finally do the division to get sc and tc
  54046. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54047. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54048. // get the difference of the two closest points
  54049. var qtc = v.multiplyByFloats(tc, tc, tc);
  54050. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54051. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54052. if (isIntersected) {
  54053. return qtc.length();
  54054. }
  54055. return -1;
  54056. };
  54057. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54058. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54059. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54060. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54061. this.direction.normalize();
  54062. return this;
  54063. };
  54064. // Statics
  54065. Ray.Zero = function () {
  54066. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54067. };
  54068. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54069. var result = Ray.Zero();
  54070. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54071. };
  54072. /**
  54073. * 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
  54074. * transformed to the given world matrix.
  54075. * @param origin The origin point
  54076. * @param end The end point
  54077. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54078. */
  54079. Ray.CreateNewFromTo = function (origin, end, world) {
  54080. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54081. var direction = end.subtract(origin);
  54082. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54083. direction.normalize();
  54084. return Ray.Transform(new Ray(origin, direction, length), world);
  54085. };
  54086. Ray.Transform = function (ray, matrix) {
  54087. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54088. Ray.TransformToRef(ray, matrix, result);
  54089. return result;
  54090. };
  54091. Ray.TransformToRef = function (ray, matrix, result) {
  54092. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54093. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54094. result.length = ray.length;
  54095. var dir = result.direction;
  54096. var len = dir.length();
  54097. if (!(len === 0 || len === 1)) {
  54098. var num = 1.0 / len;
  54099. dir.x *= num;
  54100. dir.y *= num;
  54101. dir.z *= num;
  54102. result.length *= len;
  54103. }
  54104. };
  54105. Ray.smallnum = 0.00000001;
  54106. Ray.rayl = 10e8;
  54107. return Ray;
  54108. }());
  54109. BABYLON.Ray = Ray;
  54110. })(BABYLON || (BABYLON = {}));
  54111. //# sourceMappingURL=babylon.ray.js.map
  54112. var BABYLON;
  54113. (function (BABYLON) {
  54114. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54115. if (boxMin.x > sphereCenter.x + sphereRadius)
  54116. return false;
  54117. if (sphereCenter.x - sphereRadius > boxMax.x)
  54118. return false;
  54119. if (boxMin.y > sphereCenter.y + sphereRadius)
  54120. return false;
  54121. if (sphereCenter.y - sphereRadius > boxMax.y)
  54122. return false;
  54123. if (boxMin.z > sphereCenter.z + sphereRadius)
  54124. return false;
  54125. if (sphereCenter.z - sphereRadius > boxMax.z)
  54126. return false;
  54127. return true;
  54128. };
  54129. var getLowestRoot = (function () {
  54130. var result = { root: 0, found: false };
  54131. return function (a, b, c, maxR) {
  54132. result.root = 0;
  54133. result.found = false;
  54134. var determinant = b * b - 4.0 * a * c;
  54135. if (determinant < 0)
  54136. return result;
  54137. var sqrtD = Math.sqrt(determinant);
  54138. var r1 = (-b - sqrtD) / (2.0 * a);
  54139. var r2 = (-b + sqrtD) / (2.0 * a);
  54140. if (r1 > r2) {
  54141. var temp = r2;
  54142. r2 = r1;
  54143. r1 = temp;
  54144. }
  54145. if (r1 > 0 && r1 < maxR) {
  54146. result.root = r1;
  54147. result.found = true;
  54148. return result;
  54149. }
  54150. if (r2 > 0 && r2 < maxR) {
  54151. result.root = r2;
  54152. result.found = true;
  54153. return result;
  54154. }
  54155. return result;
  54156. };
  54157. })();
  54158. var Collider = /** @class */ (function () {
  54159. function Collider() {
  54160. this._collisionPoint = BABYLON.Vector3.Zero();
  54161. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54162. this._tempVector = BABYLON.Vector3.Zero();
  54163. this._tempVector2 = BABYLON.Vector3.Zero();
  54164. this._tempVector3 = BABYLON.Vector3.Zero();
  54165. this._tempVector4 = BABYLON.Vector3.Zero();
  54166. this._edge = BABYLON.Vector3.Zero();
  54167. this._baseToVertex = BABYLON.Vector3.Zero();
  54168. this._destinationPoint = BABYLON.Vector3.Zero();
  54169. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54170. this._displacementVector = BABYLON.Vector3.Zero();
  54171. this._radius = BABYLON.Vector3.One();
  54172. this._retry = 0;
  54173. this._basePointWorld = BABYLON.Vector3.Zero();
  54174. this._velocityWorld = BABYLON.Vector3.Zero();
  54175. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54176. this._collisionMask = -1;
  54177. }
  54178. Object.defineProperty(Collider.prototype, "collisionMask", {
  54179. get: function () {
  54180. return this._collisionMask;
  54181. },
  54182. set: function (mask) {
  54183. this._collisionMask = !isNaN(mask) ? mask : -1;
  54184. },
  54185. enumerable: true,
  54186. configurable: true
  54187. });
  54188. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54189. /**
  54190. * Gets the plane normal used to compute the sliding response (in local space)
  54191. */
  54192. get: function () {
  54193. return this._slidePlaneNormal;
  54194. },
  54195. enumerable: true,
  54196. configurable: true
  54197. });
  54198. // Methods
  54199. Collider.prototype._initialize = function (source, dir, e) {
  54200. this._velocity = dir;
  54201. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54202. this._basePoint = source;
  54203. source.multiplyToRef(this._radius, this._basePointWorld);
  54204. dir.multiplyToRef(this._radius, this._velocityWorld);
  54205. this._velocityWorldLength = this._velocityWorld.length();
  54206. this._epsilon = e;
  54207. this.collisionFound = false;
  54208. };
  54209. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54210. pa.subtractToRef(point, this._tempVector);
  54211. pb.subtractToRef(point, this._tempVector2);
  54212. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54213. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54214. if (d < 0)
  54215. return false;
  54216. pc.subtractToRef(point, this._tempVector3);
  54217. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54218. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54219. if (d < 0)
  54220. return false;
  54221. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54222. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54223. return d >= 0;
  54224. };
  54225. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54226. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54227. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54228. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54229. return false;
  54230. }
  54231. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54232. return false;
  54233. return true;
  54234. };
  54235. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54236. var t0;
  54237. var embeddedInPlane = false;
  54238. //defensive programming, actually not needed.
  54239. if (!trianglePlaneArray) {
  54240. trianglePlaneArray = [];
  54241. }
  54242. if (!trianglePlaneArray[faceIndex]) {
  54243. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54244. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54245. }
  54246. var trianglePlane = trianglePlaneArray[faceIndex];
  54247. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54248. return;
  54249. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54250. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54251. if (normalDotVelocity == 0) {
  54252. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54253. return;
  54254. embeddedInPlane = true;
  54255. t0 = 0;
  54256. }
  54257. else {
  54258. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54259. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54260. if (t0 > t1) {
  54261. var temp = t1;
  54262. t1 = t0;
  54263. t0 = temp;
  54264. }
  54265. if (t0 > 1.0 || t1 < 0.0)
  54266. return;
  54267. if (t0 < 0)
  54268. t0 = 0;
  54269. if (t0 > 1.0)
  54270. t0 = 1.0;
  54271. }
  54272. this._collisionPoint.copyFromFloats(0, 0, 0);
  54273. var found = false;
  54274. var t = 1.0;
  54275. if (!embeddedInPlane) {
  54276. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54277. this._velocity.scaleToRef(t0, this._tempVector);
  54278. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54279. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54280. found = true;
  54281. t = t0;
  54282. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54283. }
  54284. }
  54285. if (!found) {
  54286. var velocitySquaredLength = this._velocity.lengthSquared();
  54287. var a = velocitySquaredLength;
  54288. this._basePoint.subtractToRef(p1, this._tempVector);
  54289. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54290. var c = this._tempVector.lengthSquared() - 1.0;
  54291. var lowestRoot = getLowestRoot(a, b, c, t);
  54292. if (lowestRoot.found) {
  54293. t = lowestRoot.root;
  54294. found = true;
  54295. this._collisionPoint.copyFrom(p1);
  54296. }
  54297. this._basePoint.subtractToRef(p2, this._tempVector);
  54298. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54299. c = this._tempVector.lengthSquared() - 1.0;
  54300. lowestRoot = getLowestRoot(a, b, c, t);
  54301. if (lowestRoot.found) {
  54302. t = lowestRoot.root;
  54303. found = true;
  54304. this._collisionPoint.copyFrom(p2);
  54305. }
  54306. this._basePoint.subtractToRef(p3, this._tempVector);
  54307. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54308. c = this._tempVector.lengthSquared() - 1.0;
  54309. lowestRoot = getLowestRoot(a, b, c, t);
  54310. if (lowestRoot.found) {
  54311. t = lowestRoot.root;
  54312. found = true;
  54313. this._collisionPoint.copyFrom(p3);
  54314. }
  54315. p2.subtractToRef(p1, this._edge);
  54316. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54317. var edgeSquaredLength = this._edge.lengthSquared();
  54318. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54319. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54320. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54321. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54322. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54323. lowestRoot = getLowestRoot(a, b, c, t);
  54324. if (lowestRoot.found) {
  54325. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54326. if (f >= 0.0 && f <= 1.0) {
  54327. t = lowestRoot.root;
  54328. found = true;
  54329. this._edge.scaleInPlace(f);
  54330. p1.addToRef(this._edge, this._collisionPoint);
  54331. }
  54332. }
  54333. p3.subtractToRef(p2, this._edge);
  54334. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54335. edgeSquaredLength = this._edge.lengthSquared();
  54336. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54337. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54338. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54339. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54340. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54341. lowestRoot = getLowestRoot(a, b, c, t);
  54342. if (lowestRoot.found) {
  54343. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54344. if (f >= 0.0 && f <= 1.0) {
  54345. t = lowestRoot.root;
  54346. found = true;
  54347. this._edge.scaleInPlace(f);
  54348. p2.addToRef(this._edge, this._collisionPoint);
  54349. }
  54350. }
  54351. p1.subtractToRef(p3, this._edge);
  54352. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54353. edgeSquaredLength = this._edge.lengthSquared();
  54354. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54355. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54356. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54357. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54358. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54359. lowestRoot = getLowestRoot(a, b, c, t);
  54360. if (lowestRoot.found) {
  54361. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54362. if (f >= 0.0 && f <= 1.0) {
  54363. t = lowestRoot.root;
  54364. found = true;
  54365. this._edge.scaleInPlace(f);
  54366. p3.addToRef(this._edge, this._collisionPoint);
  54367. }
  54368. }
  54369. }
  54370. if (found) {
  54371. var distToCollision = t * this._velocity.length();
  54372. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54373. if (!this.intersectionPoint) {
  54374. this.intersectionPoint = this._collisionPoint.clone();
  54375. }
  54376. else {
  54377. this.intersectionPoint.copyFrom(this._collisionPoint);
  54378. }
  54379. this._nearestDistance = distToCollision;
  54380. this.collisionFound = true;
  54381. }
  54382. }
  54383. };
  54384. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54385. for (var i = indexStart; i < indexEnd; i += 3) {
  54386. var p1 = pts[indices[i] - decal];
  54387. var p2 = pts[indices[i + 1] - decal];
  54388. var p3 = pts[indices[i + 2] - decal];
  54389. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54390. }
  54391. };
  54392. Collider.prototype._getResponse = function (pos, vel) {
  54393. pos.addToRef(vel, this._destinationPoint);
  54394. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54395. this._basePoint.addToRef(vel, pos);
  54396. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54397. this._slidePlaneNormal.normalize();
  54398. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54399. pos.addInPlace(this._displacementVector);
  54400. this.intersectionPoint.addInPlace(this._displacementVector);
  54401. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54402. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54403. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54404. };
  54405. return Collider;
  54406. }());
  54407. BABYLON.Collider = Collider;
  54408. })(BABYLON || (BABYLON = {}));
  54409. //# sourceMappingURL=babylon.collider.js.map
  54410. var BABYLON;
  54411. (function (BABYLON) {
  54412. //WebWorker code will be inserted to this variable.
  54413. BABYLON.CollisionWorker = "";
  54414. /** Defines supported task for worker process */
  54415. var WorkerTaskType;
  54416. (function (WorkerTaskType) {
  54417. /** Initialization */
  54418. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54419. /** Update of geometry */
  54420. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54421. /** Evaluate collision */
  54422. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54423. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54424. /** Defines kind of replies returned by worker */
  54425. var WorkerReplyType;
  54426. (function (WorkerReplyType) {
  54427. /** Success */
  54428. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54429. /** Unkown error */
  54430. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54431. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54432. var CollisionCoordinatorWorker = /** @class */ (function () {
  54433. function CollisionCoordinatorWorker() {
  54434. var _this = this;
  54435. this._scaledPosition = BABYLON.Vector3.Zero();
  54436. this._scaledVelocity = BABYLON.Vector3.Zero();
  54437. this.onMeshUpdated = function (transformNode) {
  54438. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54439. };
  54440. this.onGeometryUpdated = function (geometry) {
  54441. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54442. };
  54443. this._afterRender = function () {
  54444. if (!_this._init)
  54445. return;
  54446. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54447. return;
  54448. }
  54449. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54450. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54451. if (_this._runningUpdated > 4) {
  54452. return;
  54453. }
  54454. ++_this._runningUpdated;
  54455. var payload = {
  54456. updatedMeshes: _this._addUpdateMeshesList,
  54457. updatedGeometries: _this._addUpdateGeometriesList,
  54458. removedGeometries: _this._toRemoveGeometryArray,
  54459. removedMeshes: _this._toRemoveMeshesArray
  54460. };
  54461. var message = {
  54462. payload: payload,
  54463. taskType: WorkerTaskType.UPDATE
  54464. };
  54465. var serializable = [];
  54466. for (var id in payload.updatedGeometries) {
  54467. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54468. //prepare transferables
  54469. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54470. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54471. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54472. }
  54473. }
  54474. _this._worker.postMessage(message, serializable);
  54475. _this._addUpdateMeshesList = {};
  54476. _this._addUpdateGeometriesList = {};
  54477. _this._toRemoveGeometryArray = [];
  54478. _this._toRemoveMeshesArray = [];
  54479. };
  54480. this._onMessageFromWorker = function (e) {
  54481. var returnData = e.data;
  54482. if (returnData.error != WorkerReplyType.SUCCESS) {
  54483. //TODO what errors can be returned from the worker?
  54484. BABYLON.Tools.Warn("error returned from worker!");
  54485. return;
  54486. }
  54487. switch (returnData.taskType) {
  54488. case WorkerTaskType.INIT:
  54489. _this._init = true;
  54490. //Update the worked with ALL of the scene's current state
  54491. _this._scene.meshes.forEach(function (mesh) {
  54492. _this.onMeshAdded(mesh);
  54493. });
  54494. _this._scene.getGeometries().forEach(function (geometry) {
  54495. _this.onGeometryAdded(geometry);
  54496. });
  54497. break;
  54498. case WorkerTaskType.UPDATE:
  54499. _this._runningUpdated--;
  54500. break;
  54501. case WorkerTaskType.COLLIDE:
  54502. var returnPayload = returnData.payload;
  54503. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54504. return;
  54505. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54506. if (callback) {
  54507. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54508. if (mesh) {
  54509. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54510. }
  54511. }
  54512. //cleanup
  54513. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54514. break;
  54515. }
  54516. };
  54517. this._collisionsCallbackArray = [];
  54518. this._init = false;
  54519. this._runningUpdated = 0;
  54520. this._addUpdateMeshesList = {};
  54521. this._addUpdateGeometriesList = {};
  54522. this._toRemoveGeometryArray = [];
  54523. this._toRemoveMeshesArray = [];
  54524. }
  54525. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54526. if (!this._init)
  54527. return;
  54528. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54529. return;
  54530. position.divideToRef(collider._radius, this._scaledPosition);
  54531. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54532. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54533. var payload = {
  54534. collider: {
  54535. position: this._scaledPosition.asArray(),
  54536. velocity: this._scaledVelocity.asArray(),
  54537. radius: collider._radius.asArray()
  54538. },
  54539. collisionId: collisionIndex,
  54540. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54541. maximumRetry: maximumRetry
  54542. };
  54543. var message = {
  54544. payload: payload,
  54545. taskType: WorkerTaskType.COLLIDE
  54546. };
  54547. this._worker.postMessage(message);
  54548. };
  54549. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54550. this._scene = scene;
  54551. this._scene.registerAfterRender(this._afterRender);
  54552. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54553. this._worker = new Worker(workerUrl);
  54554. this._worker.onmessage = this._onMessageFromWorker;
  54555. var message = {
  54556. payload: {},
  54557. taskType: WorkerTaskType.INIT
  54558. };
  54559. this._worker.postMessage(message);
  54560. };
  54561. CollisionCoordinatorWorker.prototype.destroy = function () {
  54562. this._scene.unregisterAfterRender(this._afterRender);
  54563. this._worker.terminate();
  54564. };
  54565. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54566. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54567. this.onMeshUpdated(mesh);
  54568. };
  54569. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54570. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54571. };
  54572. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54573. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54574. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54575. this.onGeometryUpdated(geometry);
  54576. };
  54577. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54578. this._toRemoveGeometryArray.push(geometry.id);
  54579. };
  54580. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54581. var submeshes = [];
  54582. if (mesh.subMeshes) {
  54583. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54584. var boundingInfo = sm.getBoundingInfo();
  54585. return {
  54586. position: idx,
  54587. verticesStart: sm.verticesStart,
  54588. verticesCount: sm.verticesCount,
  54589. indexStart: sm.indexStart,
  54590. indexCount: sm.indexCount,
  54591. hasMaterial: !!sm.getMaterial(),
  54592. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54593. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54594. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54595. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54596. };
  54597. });
  54598. }
  54599. var geometryId = null;
  54600. if (mesh instanceof BABYLON.Mesh) {
  54601. var geometry = mesh.geometry;
  54602. geometryId = geometry ? geometry.id : null;
  54603. }
  54604. else if (mesh instanceof BABYLON.InstancedMesh) {
  54605. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54606. geometryId = geometry ? geometry.id : null;
  54607. }
  54608. var boundingInfo = mesh.getBoundingInfo();
  54609. return {
  54610. uniqueId: mesh.uniqueId,
  54611. id: mesh.id,
  54612. name: mesh.name,
  54613. geometryId: geometryId,
  54614. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54615. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54616. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54617. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54618. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54619. subMeshes: submeshes,
  54620. checkCollisions: mesh.checkCollisions
  54621. };
  54622. };
  54623. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54624. return {
  54625. id: geometry.id,
  54626. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54627. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54628. indices: new Uint32Array(geometry.getIndices() || []),
  54629. };
  54630. };
  54631. return CollisionCoordinatorWorker;
  54632. }());
  54633. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54634. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54635. function CollisionCoordinatorLegacy() {
  54636. this._scaledPosition = BABYLON.Vector3.Zero();
  54637. this._scaledVelocity = BABYLON.Vector3.Zero();
  54638. this._finalPosition = BABYLON.Vector3.Zero();
  54639. }
  54640. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54641. position.divideToRef(collider._radius, this._scaledPosition);
  54642. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54643. collider.collidedMesh = null;
  54644. collider._retry = 0;
  54645. collider._initialVelocity = this._scaledVelocity;
  54646. collider._initialPosition = this._scaledPosition;
  54647. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54648. this._finalPosition.multiplyInPlace(collider._radius);
  54649. //run the callback
  54650. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54651. };
  54652. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54653. this._scene = scene;
  54654. };
  54655. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54656. //Legacy need no destruction method.
  54657. };
  54658. //No update in legacy mode
  54659. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54660. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54661. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54662. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54663. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54664. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54665. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54666. if (excludedMesh === void 0) { excludedMesh = null; }
  54667. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54668. if (collider._retry >= maximumRetry) {
  54669. finalPosition.copyFrom(position);
  54670. return;
  54671. }
  54672. // Check if this is a mesh else camera or -1
  54673. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54674. collider._initialize(position, velocity, closeDistance);
  54675. // Check all meshes
  54676. for (var index = 0; index < this._scene.meshes.length; index++) {
  54677. var mesh = this._scene.meshes[index];
  54678. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54679. mesh._checkCollision(collider);
  54680. }
  54681. }
  54682. if (!collider.collisionFound) {
  54683. position.addToRef(velocity, finalPosition);
  54684. return;
  54685. }
  54686. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54687. collider._getResponse(position, velocity);
  54688. }
  54689. if (velocity.length() <= closeDistance) {
  54690. finalPosition.copyFrom(position);
  54691. return;
  54692. }
  54693. collider._retry++;
  54694. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54695. };
  54696. return CollisionCoordinatorLegacy;
  54697. }());
  54698. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54699. })(BABYLON || (BABYLON = {}));
  54700. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54701. var BABYLON;
  54702. (function (BABYLON) {
  54703. /**
  54704. * A particle represents one of the element emitted by a particle system.
  54705. * This is mainly define by its coordinates, direction, velocity and age.
  54706. */
  54707. var Particle = /** @class */ (function () {
  54708. /**
  54709. * Creates a new instance Particle
  54710. * @param particleSystem the particle system the particle belongs to
  54711. */
  54712. function Particle(
  54713. /**
  54714. * particleSystem the particle system the particle belongs to.
  54715. */
  54716. particleSystem) {
  54717. this.particleSystem = particleSystem;
  54718. /**
  54719. * The world position of the particle in the scene.
  54720. */
  54721. this.position = BABYLON.Vector3.Zero();
  54722. /**
  54723. * The world direction of the particle in the scene.
  54724. */
  54725. this.direction = BABYLON.Vector3.Zero();
  54726. /**
  54727. * The color of the particle.
  54728. */
  54729. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54730. /**
  54731. * The color change of the particle per step.
  54732. */
  54733. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54734. /**
  54735. * Defines how long will the life of the particle be.
  54736. */
  54737. this.lifeTime = 1.0;
  54738. /**
  54739. * The current age of the particle.
  54740. */
  54741. this.age = 0;
  54742. /**
  54743. * The current size of the particle.
  54744. */
  54745. this.size = 0;
  54746. /**
  54747. * The current scale of the particle.
  54748. */
  54749. this.scale = new BABYLON.Vector2(1, 1);
  54750. /**
  54751. * The current angle of the particle.
  54752. */
  54753. this.angle = 0;
  54754. /**
  54755. * Defines how fast is the angle changing.
  54756. */
  54757. this.angularSpeed = 0;
  54758. /**
  54759. * Defines the cell index used by the particle to be rendered from a sprite.
  54760. */
  54761. this.cellIndex = 0;
  54762. /** @hidden */
  54763. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54764. /** @hidden */
  54765. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54766. /** @hidden */
  54767. this._currentSize1 = 0;
  54768. /** @hidden */
  54769. this._currentSize2 = 0;
  54770. /** @hidden */
  54771. this._currentAngularSpeed1 = 0;
  54772. /** @hidden */
  54773. this._currentAngularSpeed2 = 0;
  54774. /** @hidden */
  54775. this._currentVelocity1 = 0;
  54776. /** @hidden */
  54777. this._currentVelocity2 = 0;
  54778. if (!this.particleSystem.isAnimationSheetEnabled) {
  54779. return;
  54780. }
  54781. this.updateCellInfoFromSystem();
  54782. }
  54783. Particle.prototype.updateCellInfoFromSystem = function () {
  54784. this.cellIndex = this.particleSystem.startSpriteCellID;
  54785. };
  54786. /**
  54787. * Defines how the sprite cell index is updated for the particle
  54788. */
  54789. Particle.prototype.updateCellIndex = function () {
  54790. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54791. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54792. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54793. };
  54794. /**
  54795. * Copy the properties of particle to another one.
  54796. * @param other the particle to copy the information to.
  54797. */
  54798. Particle.prototype.copyTo = function (other) {
  54799. other.position.copyFrom(this.position);
  54800. if (this._initialDirection) {
  54801. if (other._initialDirection) {
  54802. other._initialDirection.copyFrom(this._initialDirection);
  54803. }
  54804. else {
  54805. other._initialDirection = this._initialDirection.clone();
  54806. }
  54807. }
  54808. else {
  54809. other._initialDirection = null;
  54810. }
  54811. other.direction.copyFrom(this.direction);
  54812. other.color.copyFrom(this.color);
  54813. other.colorStep.copyFrom(this.colorStep);
  54814. other.lifeTime = this.lifeTime;
  54815. other.age = this.age;
  54816. other.size = this.size;
  54817. other.scale.copyFrom(this.scale);
  54818. other.angle = this.angle;
  54819. other.angularSpeed = this.angularSpeed;
  54820. other.particleSystem = this.particleSystem;
  54821. other.cellIndex = this.cellIndex;
  54822. if (this._currentColorGradient) {
  54823. other._currentColorGradient = this._currentColorGradient;
  54824. other._currentColor1.copyFrom(this._currentColor1);
  54825. other._currentColor2.copyFrom(this._currentColor2);
  54826. }
  54827. if (this._currentSizeGradient) {
  54828. other._currentSizeGradient = this._currentSizeGradient;
  54829. other._currentSize1 = this._currentSize1;
  54830. other._currentSize2 = this._currentSize2;
  54831. }
  54832. if (this._currentAngularSpeedGradient) {
  54833. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54834. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54835. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54836. }
  54837. if (this._currentVelocityGradient) {
  54838. other._currentVelocityGradient = this._currentVelocityGradient;
  54839. other._currentVelocity1 = this._currentVelocity1;
  54840. other._currentVelocity2 = this._currentVelocity2;
  54841. }
  54842. if (this.particleSystem.isAnimationSheetEnabled) {
  54843. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54844. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54845. }
  54846. };
  54847. return Particle;
  54848. }());
  54849. BABYLON.Particle = Particle;
  54850. })(BABYLON || (BABYLON = {}));
  54851. //# sourceMappingURL=babylon.particle.js.map
  54852. var BABYLON;
  54853. (function (BABYLON) {
  54854. /**
  54855. * This represents a particle system in Babylon.
  54856. * 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.
  54857. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54858. * @example https://doc.babylonjs.com/babylon101/particles
  54859. */
  54860. var ParticleSystem = /** @class */ (function () {
  54861. /**
  54862. * Instantiates a particle system.
  54863. * 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.
  54864. * @param name The name of the particle system
  54865. * @param capacity The max number of particles alive at the same time
  54866. * @param scene The scene the particle system belongs to
  54867. * @param customEffect a custom effect used to change the way particles are rendered by default
  54868. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54869. * @param epsilon Offset used to render the particles
  54870. */
  54871. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54872. if (customEffect === void 0) { customEffect = null; }
  54873. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54874. if (epsilon === void 0) { epsilon = 0.01; }
  54875. var _this = this;
  54876. /**
  54877. * List of animations used by the particle system.
  54878. */
  54879. this.animations = [];
  54880. /**
  54881. * The rendering group used by the Particle system to chose when to render.
  54882. */
  54883. this.renderingGroupId = 0;
  54884. /**
  54885. * The emitter represents the Mesh or position we are attaching the particle system to.
  54886. */
  54887. this.emitter = null;
  54888. /**
  54889. * The maximum number of particles to emit per frame
  54890. */
  54891. this.emitRate = 10;
  54892. /**
  54893. * If you want to launch only a few particles at once, that can be done, as well.
  54894. */
  54895. this.manualEmitCount = -1;
  54896. /**
  54897. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54898. */
  54899. this.updateSpeed = 0.01;
  54900. /**
  54901. * The amount of time the particle system is running (depends of the overall update speed).
  54902. */
  54903. this.targetStopDuration = 0;
  54904. /**
  54905. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54906. */
  54907. this.disposeOnStop = false;
  54908. /**
  54909. * Minimum power of emitting particles.
  54910. */
  54911. this.minEmitPower = 1;
  54912. /**
  54913. * Maximum power of emitting particles.
  54914. */
  54915. this.maxEmitPower = 1;
  54916. /**
  54917. * Minimum life time of emitting particles.
  54918. */
  54919. this.minLifeTime = 1;
  54920. /**
  54921. * Maximum life time of emitting particles.
  54922. */
  54923. this.maxLifeTime = 1;
  54924. /**
  54925. * Minimum Size of emitting particles.
  54926. */
  54927. this.minSize = 1;
  54928. /**
  54929. * Maximum Size of emitting particles.
  54930. */
  54931. this.maxSize = 1;
  54932. /**
  54933. * Minimum scale of emitting particles on X axis.
  54934. */
  54935. this.minScaleX = 1;
  54936. /**
  54937. * Maximum scale of emitting particles on X axis.
  54938. */
  54939. this.maxScaleX = 1;
  54940. /**
  54941. * Minimum scale of emitting particles on Y axis.
  54942. */
  54943. this.minScaleY = 1;
  54944. /**
  54945. * Maximum scale of emitting particles on Y axis.
  54946. */
  54947. this.maxScaleY = 1;
  54948. /**
  54949. * Gets or sets the minimal initial rotation in radians.
  54950. */
  54951. this.minInitialRotation = 0;
  54952. /**
  54953. * Gets or sets the maximal initial rotation in radians.
  54954. */
  54955. this.maxInitialRotation = 0;
  54956. /**
  54957. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54958. */
  54959. this.minAngularSpeed = 0;
  54960. /**
  54961. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54962. */
  54963. this.maxAngularSpeed = 0;
  54964. /**
  54965. * The layer mask we are rendering the particles through.
  54966. */
  54967. this.layerMask = 0x0FFFFFFF;
  54968. /**
  54969. * This can help using your own shader to render the particle system.
  54970. * The according effect will be created
  54971. */
  54972. this.customShader = null;
  54973. /**
  54974. * By default particle system starts as soon as they are created. This prevents the
  54975. * automatic start to happen and let you decide when to start emitting particles.
  54976. */
  54977. this.preventAutoStart = false;
  54978. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  54979. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  54980. /**
  54981. * Callback triggered when the particle animation is ending.
  54982. */
  54983. this.onAnimationEnd = null;
  54984. /**
  54985. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  54986. */
  54987. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  54988. /**
  54989. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  54990. * to override the particles.
  54991. */
  54992. this.forceDepthWrite = false;
  54993. /**
  54994. * You can use gravity if you want to give an orientation to your particles.
  54995. */
  54996. this.gravity = BABYLON.Vector3.Zero();
  54997. this._colorGradients = null;
  54998. this._sizeGradients = null;
  54999. this._lifeTimeGradients = null;
  55000. this._angularSpeedGradients = null;
  55001. this._velocityGradients = null;
  55002. /**
  55003. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55004. */
  55005. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55006. /**
  55007. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55008. */
  55009. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55010. /**
  55011. * Color the particle will have at the end of its lifetime
  55012. */
  55013. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55014. /**
  55015. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55016. */
  55017. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55018. /**
  55019. * 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)
  55020. */
  55021. this.spriteCellChangeSpeed = 1;
  55022. /**
  55023. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55024. */
  55025. this.startSpriteCellID = 0;
  55026. /**
  55027. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55028. */
  55029. this.endSpriteCellID = 0;
  55030. /**
  55031. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55032. */
  55033. this.spriteCellWidth = 0;
  55034. /**
  55035. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55036. */
  55037. this.spriteCellHeight = 0;
  55038. /** 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 */
  55039. this.preWarmCycles = 0;
  55040. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55041. this.preWarmStepOffset = 1;
  55042. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55043. this.translationPivot = new BABYLON.Vector2(0, 0);
  55044. /**
  55045. * An event triggered when the system is disposed
  55046. */
  55047. this.onDisposeObservable = new BABYLON.Observable();
  55048. /**
  55049. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55050. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55051. */
  55052. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55053. this._particles = new Array();
  55054. this._stockParticles = new Array();
  55055. this._newPartsExcess = 0;
  55056. this._vertexBuffers = {};
  55057. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55058. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55059. this._scaledDirection = BABYLON.Vector3.Zero();
  55060. this._scaledGravity = BABYLON.Vector3.Zero();
  55061. this._currentRenderId = -1;
  55062. this._useInstancing = false;
  55063. this._started = false;
  55064. this._stopped = false;
  55065. this._actualFrame = 0;
  55066. this._isBillboardBased = true;
  55067. // start of sub system methods
  55068. /**
  55069. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55070. * Its lifetime will start back at 0.
  55071. */
  55072. this.recycleParticle = function (particle) {
  55073. var lastParticle = _this._particles.pop();
  55074. if (lastParticle !== particle) {
  55075. lastParticle.copyTo(particle);
  55076. }
  55077. _this._stockParticles.push(lastParticle);
  55078. };
  55079. this._createParticle = function () {
  55080. var particle;
  55081. if (_this._stockParticles.length !== 0) {
  55082. particle = _this._stockParticles.pop();
  55083. particle.age = 0;
  55084. particle._currentColorGradient = null;
  55085. particle.cellIndex = _this.startSpriteCellID;
  55086. }
  55087. else {
  55088. particle = new BABYLON.Particle(_this);
  55089. }
  55090. return particle;
  55091. };
  55092. this._emitFromParticle = function (particle) {
  55093. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55094. return;
  55095. }
  55096. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55097. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55098. subSystem._rootParticleSystem = _this;
  55099. _this.activeSubSystems.push(subSystem);
  55100. subSystem.start();
  55101. };
  55102. this.id = name;
  55103. this.name = name;
  55104. this._capacity = capacity;
  55105. this._epsilon = epsilon;
  55106. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55107. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55108. this._customEffect = customEffect;
  55109. scene.particleSystems.push(this);
  55110. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55111. this._createIndexBuffer();
  55112. this._createVertexBuffers();
  55113. // Default emitter type
  55114. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55115. this.updateFunction = function (particles) {
  55116. var noiseTextureData = null;
  55117. var noiseTextureSize = null;
  55118. if (_this.noiseTexture) { // We need to get texture data back to CPU
  55119. noiseTextureData = (_this.noiseTexture.readPixels());
  55120. noiseTextureSize = _this.noiseTexture.getSize();
  55121. }
  55122. var _loop_1 = function () {
  55123. particle = particles[index];
  55124. particle.age += _this._scaledUpdateSpeed;
  55125. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55126. _this._emitFromParticle(particle);
  55127. _this.recycleParticle(particle);
  55128. index--;
  55129. return "continue";
  55130. }
  55131. else {
  55132. var ratio = particle.age / particle.lifeTime;
  55133. // Color
  55134. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55135. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55136. if (currentGradient !== particle._currentColorGradient) {
  55137. particle._currentColor1.copyFrom(particle._currentColor2);
  55138. nextGradient.getColorToRef(particle._currentColor2);
  55139. particle._currentColorGradient = currentGradient;
  55140. }
  55141. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55142. });
  55143. }
  55144. else {
  55145. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55146. particle.color.addInPlace(_this._scaledColorStep);
  55147. if (particle.color.a < 0) {
  55148. particle.color.a = 0;
  55149. }
  55150. }
  55151. // Angular speed
  55152. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55153. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55154. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55155. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55156. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55157. particle._currentAngularSpeedGradient = currentGradient;
  55158. }
  55159. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55160. });
  55161. }
  55162. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55163. // Direction
  55164. var directionScale_1 = _this._scaledUpdateSpeed;
  55165. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55166. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55167. if (currentGradient !== particle._currentVelocityGradient) {
  55168. particle._currentVelocity1 = particle._currentVelocity2;
  55169. particle._currentVelocity2 = nextGradient.getFactor();
  55170. particle._currentVelocityGradient = currentGradient;
  55171. }
  55172. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55173. });
  55174. }
  55175. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55176. particle.position.addInPlace(_this._scaledDirection);
  55177. // Noise
  55178. if (noiseTextureData && noiseTextureSize) {
  55179. var localPosition = BABYLON.Tmp.Vector3[0];
  55180. var emitterPosition = BABYLON.Tmp.Vector3[1];
  55181. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  55182. particle.position.subtractToRef(emitterPosition, localPosition);
  55183. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55184. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55185. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  55186. var force = BABYLON.Tmp.Vector3[0];
  55187. var scaledForce = BABYLON.Tmp.Vector3[1];
  55188. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  55189. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  55190. particle.direction.addInPlace(scaledForce);
  55191. }
  55192. // Gravity
  55193. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55194. particle.direction.addInPlace(_this._scaledGravity);
  55195. // Size
  55196. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55197. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55198. if (currentGradient !== particle._currentSizeGradient) {
  55199. particle._currentSize1 = particle._currentSize2;
  55200. particle._currentSize2 = nextGradient.getFactor();
  55201. particle._currentSizeGradient = currentGradient;
  55202. }
  55203. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55204. });
  55205. }
  55206. if (_this._isAnimationSheetEnabled) {
  55207. particle.updateCellIndex();
  55208. }
  55209. }
  55210. };
  55211. var particle;
  55212. for (var index = 0; index < particles.length; index++) {
  55213. _loop_1();
  55214. }
  55215. };
  55216. }
  55217. /**
  55218. * Gets the current list of color gradients.
  55219. * You must use addColorGradient and removeColorGradient to udpate this list
  55220. * @returns the list of color gradients
  55221. */
  55222. ParticleSystem.prototype.getColorGradients = function () {
  55223. return this._colorGradients;
  55224. };
  55225. /**
  55226. * Gets the current list of size gradients.
  55227. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55228. * @returns the list of size gradients
  55229. */
  55230. ParticleSystem.prototype.getSizeGradients = function () {
  55231. return this._sizeGradients;
  55232. };
  55233. /**
  55234. * Gets the current list of life time gradients.
  55235. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55236. * @returns the list of life time gradients
  55237. */
  55238. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55239. return this._lifeTimeGradients;
  55240. };
  55241. /**
  55242. * Gets the current list of angular speed gradients.
  55243. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55244. * @returns the list of angular speed gradients
  55245. */
  55246. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55247. return this._angularSpeedGradients;
  55248. };
  55249. /**
  55250. * Gets the current list of velocity gradients.
  55251. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55252. * @returns the list of velocity gradients
  55253. */
  55254. ParticleSystem.prototype.getVelocityGradients = function () {
  55255. return this._velocityGradients;
  55256. };
  55257. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55258. /**
  55259. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55260. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55261. */
  55262. get: function () {
  55263. if (this.particleEmitterType.direction1) {
  55264. return this.particleEmitterType.direction1;
  55265. }
  55266. return BABYLON.Vector3.Zero();
  55267. },
  55268. set: function (value) {
  55269. if (this.particleEmitterType.direction1) {
  55270. this.particleEmitterType.direction1 = value;
  55271. }
  55272. },
  55273. enumerable: true,
  55274. configurable: true
  55275. });
  55276. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55277. /**
  55278. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55279. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55280. */
  55281. get: function () {
  55282. if (this.particleEmitterType.direction2) {
  55283. return this.particleEmitterType.direction2;
  55284. }
  55285. return BABYLON.Vector3.Zero();
  55286. },
  55287. set: function (value) {
  55288. if (this.particleEmitterType.direction2) {
  55289. this.particleEmitterType.direction2 = value;
  55290. }
  55291. },
  55292. enumerable: true,
  55293. configurable: true
  55294. });
  55295. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55296. /**
  55297. * 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.
  55298. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55299. */
  55300. get: function () {
  55301. if (this.particleEmitterType.minEmitBox) {
  55302. return this.particleEmitterType.minEmitBox;
  55303. }
  55304. return BABYLON.Vector3.Zero();
  55305. },
  55306. set: function (value) {
  55307. if (this.particleEmitterType.minEmitBox) {
  55308. this.particleEmitterType.minEmitBox = value;
  55309. }
  55310. },
  55311. enumerable: true,
  55312. configurable: true
  55313. });
  55314. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55315. /**
  55316. * 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.
  55317. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55318. */
  55319. get: function () {
  55320. if (this.particleEmitterType.maxEmitBox) {
  55321. return this.particleEmitterType.maxEmitBox;
  55322. }
  55323. return BABYLON.Vector3.Zero();
  55324. },
  55325. set: function (value) {
  55326. if (this.particleEmitterType.maxEmitBox) {
  55327. this.particleEmitterType.maxEmitBox = value;
  55328. }
  55329. },
  55330. enumerable: true,
  55331. configurable: true
  55332. });
  55333. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55334. /**
  55335. * Sets a callback that will be triggered when the system is disposed
  55336. */
  55337. set: function (callback) {
  55338. if (this._onDisposeObserver) {
  55339. this.onDisposeObservable.remove(this._onDisposeObserver);
  55340. }
  55341. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55342. },
  55343. enumerable: true,
  55344. configurable: true
  55345. });
  55346. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55347. /**
  55348. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55349. */
  55350. get: function () {
  55351. return this._isAnimationSheetEnabled;
  55352. },
  55353. enumerable: true,
  55354. configurable: true
  55355. });
  55356. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55357. /**
  55358. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55359. */
  55360. get: function () {
  55361. return this._isBillboardBased;
  55362. },
  55363. set: function (value) {
  55364. if (this._isBillboardBased === value) {
  55365. return;
  55366. }
  55367. this._isBillboardBased = value;
  55368. this._resetEffect();
  55369. },
  55370. enumerable: true,
  55371. configurable: true
  55372. });
  55373. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55374. //end of Sub-emitter
  55375. /**
  55376. * Gets the current list of active particles
  55377. */
  55378. get: function () {
  55379. return this._particles;
  55380. },
  55381. enumerable: true,
  55382. configurable: true
  55383. });
  55384. /**
  55385. * Returns the string "ParticleSystem"
  55386. * @returns a string containing the class name
  55387. */
  55388. ParticleSystem.prototype.getClassName = function () {
  55389. return "ParticleSystem";
  55390. };
  55391. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  55392. u = Math.abs(u) * 0.5 + 0.5;
  55393. v = Math.abs(v) * 0.5 + 0.5;
  55394. var wrappedU = ((u * width) % width) | 0;
  55395. var wrappedV = ((v * height) % height) | 0;
  55396. var position = (wrappedU + wrappedV * width) * 4;
  55397. return pixels[position] / 255;
  55398. };
  55399. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55400. var newGradient = new BABYLON.FactorGradient();
  55401. newGradient.gradient = gradient;
  55402. newGradient.factor1 = factor;
  55403. newGradient.factor2 = factor2;
  55404. factorGradients.push(newGradient);
  55405. factorGradients.sort(function (a, b) {
  55406. if (a.gradient < b.gradient) {
  55407. return -1;
  55408. }
  55409. else if (a.gradient > b.gradient) {
  55410. return 1;
  55411. }
  55412. return 0;
  55413. });
  55414. };
  55415. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55416. if (!factorGradients) {
  55417. return;
  55418. }
  55419. var index = 0;
  55420. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55421. var factorGradient = factorGradients_1[_i];
  55422. if (factorGradient.gradient === gradient) {
  55423. factorGradients.splice(index, 1);
  55424. break;
  55425. }
  55426. index++;
  55427. }
  55428. };
  55429. /**
  55430. * Adds a new life time gradient
  55431. * @param gradient defines the gradient to use (between 0 and 1)
  55432. * @param factor defines the life time factor to affect to the specified gradient
  55433. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55434. * @returns the current particle system
  55435. */
  55436. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55437. if (!this._lifeTimeGradients) {
  55438. this._lifeTimeGradients = [];
  55439. }
  55440. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55441. return this;
  55442. };
  55443. /**
  55444. * Remove a specific life time gradient
  55445. * @param gradient defines the gradient to remove
  55446. * @returns the current particle system
  55447. */
  55448. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55449. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55450. return this;
  55451. };
  55452. /**
  55453. * Adds a new size gradient
  55454. * @param gradient defines the gradient to use (between 0 and 1)
  55455. * @param factor defines the size factor to affect to the specified gradient
  55456. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55457. * @returns the current particle system
  55458. */
  55459. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55460. if (!this._sizeGradients) {
  55461. this._sizeGradients = [];
  55462. }
  55463. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55464. return this;
  55465. };
  55466. /**
  55467. * Remove a specific size gradient
  55468. * @param gradient defines the gradient to remove
  55469. * @returns the current particle system
  55470. */
  55471. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55472. this._removeFactorGradient(this._sizeGradients, gradient);
  55473. return this;
  55474. };
  55475. /**
  55476. * Adds a new angular speed gradient
  55477. * @param gradient defines the gradient to use (between 0 and 1)
  55478. * @param factor defines the size factor to affect to the specified gradient
  55479. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55480. * @returns the current particle system
  55481. */
  55482. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55483. if (!this._angularSpeedGradients) {
  55484. this._angularSpeedGradients = [];
  55485. }
  55486. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55487. return this;
  55488. };
  55489. /**
  55490. * Remove a specific angular speed gradient
  55491. * @param gradient defines the gradient to remove
  55492. * @returns the current particle system
  55493. */
  55494. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55495. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55496. return this;
  55497. };
  55498. /**
  55499. * Adds a new velocity gradient
  55500. * @param gradient defines the gradient to use (between 0 and 1)
  55501. * @param factor defines the size factor to affect to the specified gradient
  55502. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55503. * @returns the current particle system
  55504. */
  55505. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55506. if (!this._velocityGradients) {
  55507. this._velocityGradients = [];
  55508. }
  55509. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55510. return this;
  55511. };
  55512. /**
  55513. * Remove a specific velocity gradient
  55514. * @param gradient defines the gradient to remove
  55515. * @returns the current particle system
  55516. */
  55517. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55518. this._removeFactorGradient(this._velocityGradients, gradient);
  55519. return this;
  55520. };
  55521. /**
  55522. * Adds a new color gradient
  55523. * @param gradient defines the gradient to use (between 0 and 1)
  55524. * @param color defines the color to affect to the specified gradient
  55525. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55526. */
  55527. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55528. if (!this._colorGradients) {
  55529. this._colorGradients = [];
  55530. }
  55531. var colorGradient = new BABYLON.ColorGradient();
  55532. colorGradient.gradient = gradient;
  55533. colorGradient.color1 = color;
  55534. colorGradient.color2 = color2;
  55535. this._colorGradients.push(colorGradient);
  55536. this._colorGradients.sort(function (a, b) {
  55537. if (a.gradient < b.gradient) {
  55538. return -1;
  55539. }
  55540. else if (a.gradient > b.gradient) {
  55541. return 1;
  55542. }
  55543. return 0;
  55544. });
  55545. return this;
  55546. };
  55547. /**
  55548. * Remove a specific color gradient
  55549. * @param gradient defines the gradient to remove
  55550. */
  55551. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55552. if (!this._colorGradients) {
  55553. return this;
  55554. }
  55555. var index = 0;
  55556. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55557. var colorGradient = _a[_i];
  55558. if (colorGradient.gradient === gradient) {
  55559. this._colorGradients.splice(index, 1);
  55560. break;
  55561. }
  55562. index++;
  55563. }
  55564. return this;
  55565. };
  55566. ParticleSystem.prototype._resetEffect = function () {
  55567. if (this._vertexBuffer) {
  55568. this._vertexBuffer.dispose();
  55569. this._vertexBuffer = null;
  55570. }
  55571. if (this._spriteBuffer) {
  55572. this._spriteBuffer.dispose();
  55573. this._spriteBuffer = null;
  55574. }
  55575. this._createVertexBuffers();
  55576. };
  55577. ParticleSystem.prototype._createVertexBuffers = function () {
  55578. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55579. if (this._isAnimationSheetEnabled) {
  55580. this._vertexBufferSize += 1;
  55581. }
  55582. if (!this._isBillboardBased) {
  55583. this._vertexBufferSize += 3;
  55584. }
  55585. var engine = this._scene.getEngine();
  55586. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55587. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55588. var dataOffset = 0;
  55589. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55591. dataOffset += 3;
  55592. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55593. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55594. dataOffset += 4;
  55595. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55596. this._vertexBuffers["angle"] = options;
  55597. dataOffset += 1;
  55598. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55599. this._vertexBuffers["size"] = size;
  55600. dataOffset += 2;
  55601. if (this._isAnimationSheetEnabled) {
  55602. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55603. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55604. dataOffset += 1;
  55605. }
  55606. if (!this._isBillboardBased) {
  55607. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55608. this._vertexBuffers["direction"] = directionBuffer;
  55609. dataOffset += 3;
  55610. }
  55611. var offsets;
  55612. if (this._useInstancing) {
  55613. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55614. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55615. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55616. }
  55617. else {
  55618. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55619. dataOffset += 2;
  55620. }
  55621. this._vertexBuffers["offset"] = offsets;
  55622. };
  55623. ParticleSystem.prototype._createIndexBuffer = function () {
  55624. if (this._useInstancing) {
  55625. return;
  55626. }
  55627. var indices = [];
  55628. var index = 0;
  55629. for (var count = 0; count < this._capacity; count++) {
  55630. indices.push(index);
  55631. indices.push(index + 1);
  55632. indices.push(index + 2);
  55633. indices.push(index);
  55634. indices.push(index + 2);
  55635. indices.push(index + 3);
  55636. index += 4;
  55637. }
  55638. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55639. };
  55640. /**
  55641. * Gets the maximum number of particles active at the same time.
  55642. * @returns The max number of active particles.
  55643. */
  55644. ParticleSystem.prototype.getCapacity = function () {
  55645. return this._capacity;
  55646. };
  55647. /**
  55648. * Gets Wether there are still active particles in the system.
  55649. * @returns True if it is alive, otherwise false.
  55650. */
  55651. ParticleSystem.prototype.isAlive = function () {
  55652. return this._alive;
  55653. };
  55654. /**
  55655. * Gets Wether the system has been started.
  55656. * @returns True if it has been started, otherwise false.
  55657. */
  55658. ParticleSystem.prototype.isStarted = function () {
  55659. return this._started;
  55660. };
  55661. /**
  55662. * Starts the particle system and begins to emit
  55663. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  55664. */
  55665. ParticleSystem.prototype.start = function (delay) {
  55666. var _this = this;
  55667. if (delay === void 0) { delay = 0; }
  55668. if (delay) {
  55669. setTimeout(function () {
  55670. _this.start(0);
  55671. }, delay);
  55672. return;
  55673. }
  55674. this._started = true;
  55675. this._stopped = false;
  55676. this._actualFrame = 0;
  55677. if (this.subEmitters && this.subEmitters.length != 0) {
  55678. this.activeSubSystems = new Array();
  55679. }
  55680. if (this.preWarmCycles) {
  55681. for (var index = 0; index < this.preWarmCycles; index++) {
  55682. this.animate(true);
  55683. }
  55684. }
  55685. };
  55686. /**
  55687. * Stops the particle system.
  55688. * @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.
  55689. */
  55690. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55691. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55692. this._stopped = true;
  55693. if (stopSubEmitters) {
  55694. this._stopSubEmitters();
  55695. }
  55696. };
  55697. // animation sheet
  55698. /**
  55699. * Remove all active particles
  55700. */
  55701. ParticleSystem.prototype.reset = function () {
  55702. this._stockParticles = [];
  55703. this._particles = [];
  55704. };
  55705. /**
  55706. * @hidden (for internal use only)
  55707. */
  55708. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55709. var offset = index * this._vertexBufferSize;
  55710. this._vertexData[offset++] = particle.position.x;
  55711. this._vertexData[offset++] = particle.position.y;
  55712. this._vertexData[offset++] = particle.position.z;
  55713. this._vertexData[offset++] = particle.color.r;
  55714. this._vertexData[offset++] = particle.color.g;
  55715. this._vertexData[offset++] = particle.color.b;
  55716. this._vertexData[offset++] = particle.color.a;
  55717. this._vertexData[offset++] = particle.angle;
  55718. this._vertexData[offset++] = particle.scale.x * particle.size;
  55719. this._vertexData[offset++] = particle.scale.y * particle.size;
  55720. if (this._isAnimationSheetEnabled) {
  55721. this._vertexData[offset++] = particle.cellIndex;
  55722. }
  55723. if (!this._isBillboardBased) {
  55724. if (particle._initialDirection) {
  55725. this._vertexData[offset++] = particle._initialDirection.x;
  55726. this._vertexData[offset++] = particle._initialDirection.y;
  55727. this._vertexData[offset++] = particle._initialDirection.z;
  55728. }
  55729. else {
  55730. this._vertexData[offset++] = particle.direction.x;
  55731. this._vertexData[offset++] = particle.direction.y;
  55732. this._vertexData[offset++] = particle.direction.z;
  55733. }
  55734. }
  55735. if (!this._useInstancing) {
  55736. if (this._isAnimationSheetEnabled) {
  55737. if (offsetX === 0)
  55738. offsetX = this._epsilon;
  55739. else if (offsetX === 1)
  55740. offsetX = 1 - this._epsilon;
  55741. if (offsetY === 0)
  55742. offsetY = this._epsilon;
  55743. else if (offsetY === 1)
  55744. offsetY = 1 - this._epsilon;
  55745. }
  55746. this._vertexData[offset++] = offsetX;
  55747. this._vertexData[offset++] = offsetY;
  55748. }
  55749. };
  55750. ParticleSystem.prototype._stopSubEmitters = function () {
  55751. if (!this.activeSubSystems) {
  55752. return;
  55753. }
  55754. this.activeSubSystems.forEach(function (subSystem) {
  55755. subSystem.stop(true);
  55756. });
  55757. this.activeSubSystems = new Array();
  55758. };
  55759. ParticleSystem.prototype._removeFromRoot = function () {
  55760. if (!this._rootParticleSystem) {
  55761. return;
  55762. }
  55763. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55764. if (index !== -1) {
  55765. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55766. }
  55767. };
  55768. // End of sub system methods
  55769. ParticleSystem.prototype._update = function (newParticles) {
  55770. // Update current
  55771. this._alive = this._particles.length > 0;
  55772. if (this.emitter.position) {
  55773. var emitterMesh = this.emitter;
  55774. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  55775. }
  55776. else {
  55777. var emitterPosition = this.emitter;
  55778. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55779. }
  55780. this.updateFunction(this._particles);
  55781. // Add new ones
  55782. var particle;
  55783. var _loop_2 = function () {
  55784. if (this_1._particles.length === this_1._capacity) {
  55785. return "break";
  55786. }
  55787. particle = this_1._createParticle();
  55788. this_1._particles.push(particle);
  55789. // Emitter
  55790. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55791. if (this_1.startPositionFunction) {
  55792. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55793. }
  55794. else {
  55795. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  55796. }
  55797. if (this_1.startDirectionFunction) {
  55798. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55799. }
  55800. else {
  55801. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  55802. }
  55803. if (emitPower === 0) {
  55804. if (!particle._initialDirection) {
  55805. particle._initialDirection = particle.direction.clone();
  55806. }
  55807. else {
  55808. particle._initialDirection.copyFrom(particle.direction);
  55809. }
  55810. }
  55811. else {
  55812. particle._initialDirection = null;
  55813. }
  55814. particle.direction.scaleInPlace(emitPower);
  55815. // Life time
  55816. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55817. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55818. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55819. var factorGradient1 = currentGradient;
  55820. var factorGradient2 = nextGradient;
  55821. var lifeTime1 = factorGradient1.getFactor();
  55822. var lifeTime2 = factorGradient2.getFactor();
  55823. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55824. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55825. });
  55826. }
  55827. else {
  55828. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55829. }
  55830. // Size
  55831. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55832. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55833. }
  55834. else {
  55835. particle._currentSizeGradient = this_1._sizeGradients[0];
  55836. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55837. particle.size = particle._currentSize1;
  55838. if (this_1._sizeGradients.length > 1) {
  55839. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55840. }
  55841. else {
  55842. particle._currentSize2 = particle._currentSize1;
  55843. }
  55844. }
  55845. // Size and scale
  55846. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55847. // Angle
  55848. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55849. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55850. }
  55851. else {
  55852. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55853. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55854. particle._currentAngularSpeed1 = particle.angularSpeed;
  55855. if (this_1._angularSpeedGradients.length > 1) {
  55856. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55857. }
  55858. else {
  55859. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55860. }
  55861. }
  55862. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55863. // Velocity
  55864. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55865. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55866. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55867. if (this_1._velocityGradients.length > 1) {
  55868. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55869. }
  55870. else {
  55871. particle._currentVelocity2 = particle._currentVelocity1;
  55872. }
  55873. }
  55874. // Color
  55875. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55876. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55877. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55878. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55879. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55880. }
  55881. else {
  55882. particle._currentColorGradient = this_1._colorGradients[0];
  55883. particle._currentColorGradient.getColorToRef(particle.color);
  55884. particle._currentColor1.copyFrom(particle.color);
  55885. if (this_1._colorGradients.length > 1) {
  55886. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55887. }
  55888. else {
  55889. particle._currentColor2.copyFrom(particle.color);
  55890. }
  55891. }
  55892. // Sheet
  55893. if (this_1._isAnimationSheetEnabled) {
  55894. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55895. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55896. }
  55897. };
  55898. var this_1 = this, step;
  55899. for (var index = 0; index < newParticles; index++) {
  55900. var state_1 = _loop_2();
  55901. if (state_1 === "break")
  55902. break;
  55903. }
  55904. };
  55905. /** @hidden */
  55906. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55907. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55908. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55909. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55910. if (isAnimationSheetEnabled) {
  55911. attributeNamesOrOptions.push("cellIndex");
  55912. }
  55913. if (!isBillboardBased) {
  55914. attributeNamesOrOptions.push("direction");
  55915. }
  55916. return attributeNamesOrOptions;
  55917. };
  55918. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55919. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55920. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55921. if (isAnimationSheetEnabled) {
  55922. effectCreationOption.push("particlesInfos");
  55923. }
  55924. return effectCreationOption;
  55925. };
  55926. ParticleSystem.prototype._getEffect = function () {
  55927. if (this._customEffect) {
  55928. return this._customEffect;
  55929. }
  55930. ;
  55931. var defines = [];
  55932. if (this._scene.clipPlane) {
  55933. defines.push("#define CLIPPLANE");
  55934. }
  55935. if (this._isAnimationSheetEnabled) {
  55936. defines.push("#define ANIMATESHEET");
  55937. }
  55938. if (this._isBillboardBased) {
  55939. defines.push("#define BILLBOARD");
  55940. switch (this.billboardMode) {
  55941. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55942. defines.push("#define BILLBOARDY");
  55943. break;
  55944. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55945. default:
  55946. break;
  55947. }
  55948. }
  55949. // Effect
  55950. var join = defines.join("\n");
  55951. if (this._cachedDefines !== join) {
  55952. this._cachedDefines = join;
  55953. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55954. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55955. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55956. }
  55957. return this._effect;
  55958. };
  55959. /**
  55960. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55961. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55962. */
  55963. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55964. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55965. if (!this._started)
  55966. return;
  55967. if (!preWarmOnly) {
  55968. var effect = this._getEffect();
  55969. // Check
  55970. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55971. return;
  55972. if (this._currentRenderId === this._scene.getRenderId()) {
  55973. return;
  55974. }
  55975. this._currentRenderId = this._scene.getRenderId();
  55976. }
  55977. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55978. // determine the number of particles we need to create
  55979. var newParticles;
  55980. if (this.manualEmitCount > -1) {
  55981. newParticles = this.manualEmitCount;
  55982. this._newPartsExcess = 0;
  55983. this.manualEmitCount = 0;
  55984. }
  55985. else {
  55986. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55987. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55988. }
  55989. if (this._newPartsExcess > 1.0) {
  55990. newParticles += this._newPartsExcess >> 0;
  55991. this._newPartsExcess -= this._newPartsExcess >> 0;
  55992. }
  55993. this._alive = false;
  55994. if (!this._stopped) {
  55995. this._actualFrame += this._scaledUpdateSpeed;
  55996. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55997. this.stop();
  55998. }
  55999. else {
  56000. newParticles = 0;
  56001. }
  56002. this._update(newParticles);
  56003. // Stopped?
  56004. if (this._stopped) {
  56005. if (!this._alive) {
  56006. this._started = false;
  56007. if (this.onAnimationEnd) {
  56008. this.onAnimationEnd();
  56009. }
  56010. if (this.disposeOnStop) {
  56011. this._scene._toBeDisposed.push(this);
  56012. }
  56013. }
  56014. }
  56015. if (!preWarmOnly) {
  56016. // Update VBO
  56017. var offset = 0;
  56018. for (var index = 0; index < this._particles.length; index++) {
  56019. var particle = this._particles[index];
  56020. this._appendParticleVertices(offset, particle);
  56021. offset += this._useInstancing ? 1 : 4;
  56022. }
  56023. if (this._vertexBuffer) {
  56024. this._vertexBuffer.update(this._vertexData);
  56025. }
  56026. }
  56027. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56028. this.stop();
  56029. }
  56030. };
  56031. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56032. this._appendParticleVertex(offset++, particle, 0, 0);
  56033. if (!this._useInstancing) {
  56034. this._appendParticleVertex(offset++, particle, 1, 0);
  56035. this._appendParticleVertex(offset++, particle, 1, 1);
  56036. this._appendParticleVertex(offset++, particle, 0, 1);
  56037. }
  56038. };
  56039. /**
  56040. * Rebuilds the particle system.
  56041. */
  56042. ParticleSystem.prototype.rebuild = function () {
  56043. this._createIndexBuffer();
  56044. if (this._vertexBuffer) {
  56045. this._vertexBuffer._rebuild();
  56046. }
  56047. };
  56048. /**
  56049. * Is this system ready to be used/rendered
  56050. * @return true if the system is ready
  56051. */
  56052. ParticleSystem.prototype.isReady = function () {
  56053. var effect = this._getEffect();
  56054. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56055. return false;
  56056. }
  56057. return true;
  56058. };
  56059. /**
  56060. * Renders the particle system in its current state.
  56061. * @returns the current number of particles
  56062. */
  56063. ParticleSystem.prototype.render = function () {
  56064. var effect = this._getEffect();
  56065. // Check
  56066. if (!this.isReady() || !this._particles.length) {
  56067. return 0;
  56068. }
  56069. var engine = this._scene.getEngine();
  56070. // Render
  56071. engine.enableEffect(effect);
  56072. engine.setState(false);
  56073. var viewMatrix = this._scene.getViewMatrix();
  56074. effect.setTexture("diffuseSampler", this.particleTexture);
  56075. effect.setMatrix("view", viewMatrix);
  56076. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56077. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56078. var baseSize = this.particleTexture.getBaseSize();
  56079. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56080. }
  56081. effect.setVector2("translationPivot", this.translationPivot);
  56082. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56083. if (this._isBillboardBased) {
  56084. var camera = this._scene.activeCamera;
  56085. effect.setVector3("eyePosition", camera.globalPosition);
  56086. }
  56087. if (this._scene.clipPlane) {
  56088. var clipPlane = this._scene.clipPlane;
  56089. var invView = viewMatrix.clone();
  56090. invView.invert();
  56091. effect.setMatrix("invView", invView);
  56092. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56093. }
  56094. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56095. // Draw order
  56096. switch (this.blendMode) {
  56097. case ParticleSystem.BLENDMODE_ADD:
  56098. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56099. break;
  56100. case ParticleSystem.BLENDMODE_ONEONE:
  56101. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56102. break;
  56103. case ParticleSystem.BLENDMODE_STANDARD:
  56104. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56105. break;
  56106. }
  56107. if (this.forceDepthWrite) {
  56108. engine.setDepthWrite(true);
  56109. }
  56110. if (this._useInstancing) {
  56111. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56112. engine.unbindInstanceAttributes();
  56113. }
  56114. else {
  56115. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56116. }
  56117. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56118. return this._particles.length;
  56119. };
  56120. /**
  56121. * Disposes the particle system and free the associated resources
  56122. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56123. */
  56124. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56125. if (disposeTexture === void 0) { disposeTexture = true; }
  56126. if (this._vertexBuffer) {
  56127. this._vertexBuffer.dispose();
  56128. this._vertexBuffer = null;
  56129. }
  56130. if (this._spriteBuffer) {
  56131. this._spriteBuffer.dispose();
  56132. this._spriteBuffer = null;
  56133. }
  56134. if (this._indexBuffer) {
  56135. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56136. this._indexBuffer = null;
  56137. }
  56138. if (disposeTexture && this.particleTexture) {
  56139. this.particleTexture.dispose();
  56140. this.particleTexture = null;
  56141. }
  56142. if (disposeTexture && this.noiseTexture) {
  56143. this.noiseTexture.dispose();
  56144. this.noiseTexture = null;
  56145. }
  56146. this._removeFromRoot();
  56147. // Remove from scene
  56148. var index = this._scene.particleSystems.indexOf(this);
  56149. if (index > -1) {
  56150. this._scene.particleSystems.splice(index, 1);
  56151. }
  56152. // Callback
  56153. this.onDisposeObservable.notifyObservers(this);
  56154. this.onDisposeObservable.clear();
  56155. };
  56156. /**
  56157. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56158. * @param radius The radius of the sphere to emit from
  56159. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56160. * @returns the emitter
  56161. */
  56162. ParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56163. if (radius === void 0) { radius = 1; }
  56164. if (radiusRange === void 0) { radiusRange = 1; }
  56165. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56166. this.particleEmitterType = particleEmitter;
  56167. return particleEmitter;
  56168. };
  56169. /**
  56170. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56171. * @param radius The radius of the sphere to emit from
  56172. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56173. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56174. * @returns the emitter
  56175. */
  56176. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56177. if (radius === void 0) { radius = 1; }
  56178. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56179. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56180. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56181. this.particleEmitterType = particleEmitter;
  56182. return particleEmitter;
  56183. };
  56184. /**
  56185. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56186. * @param radius The radius of the cone to emit from
  56187. * @param angle The base angle of the cone
  56188. * @returns the emitter
  56189. */
  56190. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56191. if (radius === void 0) { radius = 1; }
  56192. if (angle === void 0) { angle = Math.PI / 4; }
  56193. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56194. this.particleEmitterType = particleEmitter;
  56195. return particleEmitter;
  56196. };
  56197. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  56198. /**
  56199. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56200. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56201. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56202. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56203. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56204. * @returns the emitter
  56205. */
  56206. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56207. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56208. this.particleEmitterType = particleEmitter;
  56209. this.direction1 = direction1;
  56210. this.direction2 = direction2;
  56211. this.minEmitBox = minEmitBox;
  56212. this.maxEmitBox = maxEmitBox;
  56213. return particleEmitter;
  56214. };
  56215. // Clone
  56216. /**
  56217. * Clones the particle system.
  56218. * @param name The name of the cloned object
  56219. * @param newEmitter The new emitter to use
  56220. * @returns the cloned particle system
  56221. */
  56222. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56223. var custom = null;
  56224. var program = null;
  56225. if (this.customShader != null) {
  56226. program = this.customShader;
  56227. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56228. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56229. }
  56230. else if (this._customEffect) {
  56231. custom = this._customEffect;
  56232. }
  56233. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56234. result.customShader = program;
  56235. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56236. if (newEmitter === undefined) {
  56237. newEmitter = this.emitter;
  56238. }
  56239. result.emitter = newEmitter;
  56240. if (this.particleTexture) {
  56241. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56242. }
  56243. if (!this.preventAutoStart) {
  56244. result.start();
  56245. }
  56246. return result;
  56247. };
  56248. /**
  56249. * Serializes the particle system to a JSON object.
  56250. * @returns the JSON object
  56251. */
  56252. ParticleSystem.prototype.serialize = function () {
  56253. var serializationObject = {};
  56254. ParticleSystem._Serialize(serializationObject, this);
  56255. serializationObject.textureMask = this.textureMask.asArray();
  56256. serializationObject.customShader = this.customShader;
  56257. serializationObject.preventAutoStart = this.preventAutoStart;
  56258. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56259. return serializationObject;
  56260. };
  56261. /** @hidden */
  56262. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56263. serializationObject.name = particleSystem.name;
  56264. serializationObject.id = particleSystem.id;
  56265. serializationObject.capacity = particleSystem.getCapacity();
  56266. // Emitter
  56267. if (particleSystem.emitter.position) {
  56268. var emitterMesh = particleSystem.emitter;
  56269. serializationObject.emitterId = emitterMesh.id;
  56270. }
  56271. else {
  56272. var emitterPosition = particleSystem.emitter;
  56273. serializationObject.emitter = emitterPosition.asArray();
  56274. }
  56275. // Emitter
  56276. if (particleSystem.particleEmitterType) {
  56277. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56278. }
  56279. if (particleSystem.particleTexture) {
  56280. serializationObject.textureName = particleSystem.particleTexture.name;
  56281. }
  56282. // Animations
  56283. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56284. // Particle system
  56285. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56286. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56287. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56288. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56289. serializationObject.minSize = particleSystem.minSize;
  56290. serializationObject.maxSize = particleSystem.maxSize;
  56291. serializationObject.minScaleX = particleSystem.minScaleX;
  56292. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56293. serializationObject.minScaleY = particleSystem.minScaleY;
  56294. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56295. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56296. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56297. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56298. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56299. serializationObject.emitRate = particleSystem.emitRate;
  56300. serializationObject.gravity = particleSystem.gravity.asArray();
  56301. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  56302. serializationObject.color1 = particleSystem.color1.asArray();
  56303. serializationObject.color2 = particleSystem.color2.asArray();
  56304. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56305. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56306. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56307. serializationObject.blendMode = particleSystem.blendMode;
  56308. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56309. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56310. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56311. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56312. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56313. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56314. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56315. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56316. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56317. var colorGradients = particleSystem.getColorGradients();
  56318. if (colorGradients) {
  56319. serializationObject.colorGradients = [];
  56320. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56321. var colorGradient = colorGradients_1[_i];
  56322. var serializedGradient = {
  56323. gradient: colorGradient.gradient,
  56324. color1: colorGradient.color1.asArray()
  56325. };
  56326. if (colorGradient.color2) {
  56327. serializedGradient.color2 = colorGradient.color2.asArray();
  56328. }
  56329. serializationObject.colorGradients.push(serializedGradient);
  56330. }
  56331. }
  56332. var sizeGradients = particleSystem.getSizeGradients();
  56333. if (sizeGradients) {
  56334. serializationObject.sizeGradients = [];
  56335. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56336. var sizeGradient = sizeGradients_1[_a];
  56337. var serializedGradient = {
  56338. gradient: sizeGradient.gradient,
  56339. factor1: sizeGradient.factor1
  56340. };
  56341. if (sizeGradient.factor2 !== undefined) {
  56342. serializedGradient.factor2 = sizeGradient.factor2;
  56343. }
  56344. serializationObject.sizeGradients.push(serializedGradient);
  56345. }
  56346. }
  56347. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56348. if (angularSpeedGradients) {
  56349. serializationObject.angularSpeedGradients = [];
  56350. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56351. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56352. var serializedGradient = {
  56353. gradient: angularSpeedGradient.gradient,
  56354. factor1: angularSpeedGradient.factor1
  56355. };
  56356. if (angularSpeedGradient.factor2 !== undefined) {
  56357. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56358. }
  56359. serializationObject.angularSpeedGradients.push(serializedGradient);
  56360. }
  56361. }
  56362. var velocityGradients = particleSystem.getVelocityGradients();
  56363. if (velocityGradients) {
  56364. serializationObject.velocityGradients = [];
  56365. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56366. var velocityGradient = velocityGradients_1[_c];
  56367. var serializedGradient = {
  56368. gradient: velocityGradient.gradient,
  56369. factor1: velocityGradient.factor1
  56370. };
  56371. if (velocityGradient.factor2 !== undefined) {
  56372. serializedGradient.factor2 = velocityGradient.factor2;
  56373. }
  56374. serializationObject.velocityGradients.push(serializedGradient);
  56375. }
  56376. }
  56377. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  56378. var noiseTexture = particleSystem.noiseTexture;
  56379. serializationObject.noiseTexture = noiseTexture.serialize();
  56380. }
  56381. };
  56382. /** @hidden */
  56383. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56384. // Texture
  56385. if (parsedParticleSystem.textureName) {
  56386. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56387. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56388. }
  56389. // Emitter
  56390. if (parsedParticleSystem.emitterId === undefined) {
  56391. particleSystem.emitter = BABYLON.Vector3.Zero();
  56392. }
  56393. else if (parsedParticleSystem.emitterId) {
  56394. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56395. }
  56396. else {
  56397. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56398. }
  56399. // Misc.
  56400. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56401. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56402. }
  56403. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56404. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56405. }
  56406. // Animations
  56407. if (parsedParticleSystem.animations) {
  56408. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56409. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56410. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56411. }
  56412. }
  56413. if (parsedParticleSystem.autoAnimate) {
  56414. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56415. }
  56416. // Particle system
  56417. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56418. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56419. particleSystem.minSize = parsedParticleSystem.minSize;
  56420. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56421. if (parsedParticleSystem.minScaleX) {
  56422. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56423. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56424. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56425. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56426. }
  56427. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56428. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56429. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56430. }
  56431. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56432. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56433. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56434. }
  56435. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56436. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56437. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56438. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56439. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56440. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56441. if (parsedParticleSystem.noiseStrength) {
  56442. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  56443. }
  56444. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56445. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56446. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56447. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56448. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56449. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56450. if (parsedParticleSystem.colorGradients) {
  56451. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56452. var colorGradient = _a[_i];
  56453. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56454. }
  56455. }
  56456. if (parsedParticleSystem.sizeGradients) {
  56457. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56458. var sizeGradient = _c[_b];
  56459. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56460. }
  56461. }
  56462. if (parsedParticleSystem.angularSpeedGradients) {
  56463. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56464. var angularSpeedGradient = _e[_d];
  56465. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56466. }
  56467. }
  56468. if (parsedParticleSystem.velocityGradients) {
  56469. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56470. var velocityGradient = _g[_f];
  56471. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56472. }
  56473. }
  56474. if (parsedParticleSystem.noiseTexture) {
  56475. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  56476. }
  56477. // Emitter
  56478. var emitterType;
  56479. if (parsedParticleSystem.particleEmitterType) {
  56480. switch (parsedParticleSystem.particleEmitterType.type) {
  56481. case "SphereParticleEmitter":
  56482. emitterType = new BABYLON.SphereParticleEmitter();
  56483. break;
  56484. case "SphereDirectedParticleEmitter":
  56485. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56486. break;
  56487. case "ConeEmitter":
  56488. case "ConeParticleEmitter":
  56489. emitterType = new BABYLON.ConeParticleEmitter();
  56490. break;
  56491. case "BoxEmitter":
  56492. case "BoxParticleEmitter":
  56493. default:
  56494. emitterType = new BABYLON.BoxParticleEmitter();
  56495. break;
  56496. }
  56497. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56498. }
  56499. else {
  56500. emitterType = new BABYLON.BoxParticleEmitter();
  56501. emitterType.parse(parsedParticleSystem);
  56502. }
  56503. particleSystem.particleEmitterType = emitterType;
  56504. // Animation sheet
  56505. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56506. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56507. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56508. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56509. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56510. };
  56511. /**
  56512. * Parses a JSON object to create a particle system.
  56513. * @param parsedParticleSystem The JSON object to parse
  56514. * @param scene The scene to create the particle system in
  56515. * @param rootUrl The root url to use to load external dependencies like texture
  56516. * @returns the Parsed particle system
  56517. */
  56518. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56519. var name = parsedParticleSystem.name;
  56520. var custom = null;
  56521. var program = null;
  56522. if (parsedParticleSystem.customShader) {
  56523. program = parsedParticleSystem.customShader;
  56524. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56525. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56526. }
  56527. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56528. particleSystem.customShader = program;
  56529. if (parsedParticleSystem.id) {
  56530. particleSystem.id = parsedParticleSystem.id;
  56531. }
  56532. // Auto start
  56533. if (parsedParticleSystem.preventAutoStart) {
  56534. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56535. }
  56536. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56537. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56538. if (!particleSystem.preventAutoStart) {
  56539. particleSystem.start();
  56540. }
  56541. return particleSystem;
  56542. };
  56543. /**
  56544. * Source color is added to the destination color without alpha affecting the result.
  56545. */
  56546. ParticleSystem.BLENDMODE_ONEONE = 0;
  56547. /**
  56548. * Blend current color and particle color using particle’s alpha.
  56549. */
  56550. ParticleSystem.BLENDMODE_STANDARD = 1;
  56551. /**
  56552. * Add current color and particle color multiplied by particle’s alpha.
  56553. */
  56554. ParticleSystem.BLENDMODE_ADD = 2;
  56555. return ParticleSystem;
  56556. }());
  56557. BABYLON.ParticleSystem = ParticleSystem;
  56558. })(BABYLON || (BABYLON = {}));
  56559. //# sourceMappingURL=babylon.particleSystem.js.map
  56560. var BABYLON;
  56561. (function (BABYLON) {
  56562. /**
  56563. * Particle emitter emitting particles from the inside of a box.
  56564. * It emits the particles randomly between 2 given directions.
  56565. */
  56566. var BoxParticleEmitter = /** @class */ (function () {
  56567. /**
  56568. * Creates a new instance BoxParticleEmitter
  56569. */
  56570. function BoxParticleEmitter() {
  56571. /**
  56572. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56573. */
  56574. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56575. /**
  56576. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56577. */
  56578. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56579. /**
  56580. * 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.
  56581. */
  56582. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56583. /**
  56584. * 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.
  56585. */
  56586. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56587. }
  56588. /**
  56589. * Called by the particle System when the direction is computed for the created particle.
  56590. * @param worldMatrix is the world matrix of the particle system
  56591. * @param directionToUpdate is the direction vector to update with the result
  56592. * @param particle is the particle we are computed the direction for
  56593. */
  56594. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56595. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56596. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56597. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56598. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56599. };
  56600. /**
  56601. * Called by the particle System when the position is computed for the created particle.
  56602. * @param worldMatrix is the world matrix of the particle system
  56603. * @param positionToUpdate is the position vector to update with the result
  56604. * @param particle is the particle we are computed the position for
  56605. */
  56606. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56607. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56608. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56609. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56610. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56611. };
  56612. /**
  56613. * Clones the current emitter and returns a copy of it
  56614. * @returns the new emitter
  56615. */
  56616. BoxParticleEmitter.prototype.clone = function () {
  56617. var newOne = new BoxParticleEmitter();
  56618. BABYLON.Tools.DeepCopy(this, newOne);
  56619. return newOne;
  56620. };
  56621. /**
  56622. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56623. * @param effect defines the update shader
  56624. */
  56625. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56626. effect.setVector3("direction1", this.direction1);
  56627. effect.setVector3("direction2", this.direction2);
  56628. effect.setVector3("minEmitBox", this.minEmitBox);
  56629. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56630. };
  56631. /**
  56632. * Returns a string to use to update the GPU particles update shader
  56633. * @returns a string containng the defines string
  56634. */
  56635. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56636. return "#define BOXEMITTER";
  56637. };
  56638. /**
  56639. * Returns the string "BoxParticleEmitter"
  56640. * @returns a string containing the class name
  56641. */
  56642. BoxParticleEmitter.prototype.getClassName = function () {
  56643. return "BoxParticleEmitter";
  56644. };
  56645. /**
  56646. * Serializes the particle system to a JSON object.
  56647. * @returns the JSON object
  56648. */
  56649. BoxParticleEmitter.prototype.serialize = function () {
  56650. var serializationObject = {};
  56651. serializationObject.type = this.getClassName();
  56652. serializationObject.direction1 = this.direction1.asArray();
  56653. serializationObject.direction2 = this.direction2.asArray();
  56654. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56655. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56656. return serializationObject;
  56657. };
  56658. /**
  56659. * Parse properties from a JSON object
  56660. * @param serializationObject defines the JSON object
  56661. */
  56662. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56663. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56664. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56665. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56666. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56667. };
  56668. return BoxParticleEmitter;
  56669. }());
  56670. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56671. })(BABYLON || (BABYLON = {}));
  56672. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56673. var BABYLON;
  56674. (function (BABYLON) {
  56675. /**
  56676. * Particle emitter emitting particles from the inside of a cone.
  56677. * It emits the particles alongside the cone volume from the base to the particle.
  56678. * The emission direction might be randomized.
  56679. */
  56680. var ConeParticleEmitter = /** @class */ (function () {
  56681. /**
  56682. * Creates a new instance ConeParticleEmitter
  56683. * @param radius the radius of the emission cone (1 by default)
  56684. * @param angles the cone base angle (PI by default)
  56685. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56686. */
  56687. function ConeParticleEmitter(radius, angle,
  56688. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56689. directionRandomizer) {
  56690. if (radius === void 0) { radius = 1; }
  56691. if (angle === void 0) { angle = Math.PI; }
  56692. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56693. this.directionRandomizer = directionRandomizer;
  56694. /**
  56695. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56696. */
  56697. this.radiusRange = 1;
  56698. /**
  56699. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56700. */
  56701. this.heightRange = 1;
  56702. this.angle = angle;
  56703. this.radius = radius;
  56704. }
  56705. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56706. /**
  56707. * Gets or sets the radius of the emission cone
  56708. */
  56709. get: function () {
  56710. return this._radius;
  56711. },
  56712. set: function (value) {
  56713. this._radius = value;
  56714. this._buildHeight();
  56715. },
  56716. enumerable: true,
  56717. configurable: true
  56718. });
  56719. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56720. /**
  56721. * Gets or sets the angle of the emission cone
  56722. */
  56723. get: function () {
  56724. return this._angle;
  56725. },
  56726. set: function (value) {
  56727. this._angle = value;
  56728. this._buildHeight();
  56729. },
  56730. enumerable: true,
  56731. configurable: true
  56732. });
  56733. ConeParticleEmitter.prototype._buildHeight = function () {
  56734. if (this._angle !== 0) {
  56735. this._height = this._radius / Math.tan(this._angle / 2);
  56736. }
  56737. else {
  56738. this._height = 1;
  56739. }
  56740. };
  56741. /**
  56742. * Called by the particle System when the direction is computed for the created particle.
  56743. * @param worldMatrix is the world matrix of the particle system
  56744. * @param directionToUpdate is the direction vector to update with the result
  56745. * @param particle is the particle we are computed the direction for
  56746. */
  56747. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56748. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56749. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56750. }
  56751. else {
  56752. // measure the direction Vector from the emitter to the particle.
  56753. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56754. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56755. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56756. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56757. direction.x += randX;
  56758. direction.y += randY;
  56759. direction.z += randZ;
  56760. direction.normalize();
  56761. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56762. }
  56763. };
  56764. /**
  56765. * Called by the particle System when the position is computed for the created particle.
  56766. * @param worldMatrix is the world matrix of the particle system
  56767. * @param positionToUpdate is the position vector to update with the result
  56768. * @param particle is the particle we are computed the position for
  56769. */
  56770. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56771. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56772. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56773. // Better distribution in a cone at normal angles.
  56774. h = 1 - h * h;
  56775. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56776. radius = radius * h;
  56777. var randX = radius * Math.sin(s);
  56778. var randZ = radius * Math.cos(s);
  56779. var randY = h * this._height;
  56780. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56781. };
  56782. /**
  56783. * Clones the current emitter and returns a copy of it
  56784. * @returns the new emitter
  56785. */
  56786. ConeParticleEmitter.prototype.clone = function () {
  56787. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56788. BABYLON.Tools.DeepCopy(this, newOne);
  56789. return newOne;
  56790. };
  56791. /**
  56792. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56793. * @param effect defines the update shader
  56794. */
  56795. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56796. effect.setFloat2("radius", this._radius, this.radiusRange);
  56797. effect.setFloat("coneAngle", this._angle);
  56798. effect.setFloat2("height", this._height, this.heightRange);
  56799. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56800. };
  56801. /**
  56802. * Returns a string to use to update the GPU particles update shader
  56803. * @returns a string containng the defines string
  56804. */
  56805. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56806. return "#define CONEEMITTER";
  56807. };
  56808. /**
  56809. * Returns the string "ConeParticleEmitter"
  56810. * @returns a string containing the class name
  56811. */
  56812. ConeParticleEmitter.prototype.getClassName = function () {
  56813. return "ConeParticleEmitter";
  56814. };
  56815. /**
  56816. * Serializes the particle system to a JSON object.
  56817. * @returns the JSON object
  56818. */
  56819. ConeParticleEmitter.prototype.serialize = function () {
  56820. var serializationObject = {};
  56821. serializationObject.type = this.getClassName();
  56822. serializationObject.radius = this._radius;
  56823. serializationObject.angle = this._angle;
  56824. serializationObject.directionRandomizer = this.directionRandomizer;
  56825. return serializationObject;
  56826. };
  56827. /**
  56828. * Parse properties from a JSON object
  56829. * @param serializationObject defines the JSON object
  56830. */
  56831. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56832. this.radius = serializationObject.radius;
  56833. this.angle = serializationObject.angle;
  56834. this.directionRandomizer = serializationObject.directionRandomizer;
  56835. };
  56836. return ConeParticleEmitter;
  56837. }());
  56838. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56839. })(BABYLON || (BABYLON = {}));
  56840. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56841. var BABYLON;
  56842. (function (BABYLON) {
  56843. /**
  56844. * Particle emitter emitting particles from the inside of a sphere.
  56845. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56846. */
  56847. var SphereParticleEmitter = /** @class */ (function () {
  56848. /**
  56849. * Creates a new instance SphereParticleEmitter
  56850. * @param radius the radius of the emission sphere (1 by default)
  56851. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  56852. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56853. */
  56854. function SphereParticleEmitter(
  56855. /**
  56856. * The radius of the emission sphere.
  56857. */
  56858. radius,
  56859. /**
  56860. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  56861. */
  56862. radiusRange,
  56863. /**
  56864. * How much to randomize the particle direction [0-1].
  56865. */
  56866. directionRandomizer) {
  56867. if (radius === void 0) { radius = 1; }
  56868. if (radiusRange === void 0) { radiusRange = 1; }
  56869. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56870. this.radius = radius;
  56871. this.radiusRange = radiusRange;
  56872. this.directionRandomizer = directionRandomizer;
  56873. }
  56874. /**
  56875. * Called by the particle System when the direction is computed for the created particle.
  56876. * @param worldMatrix is the world matrix of the particle system
  56877. * @param directionToUpdate is the direction vector to update with the result
  56878. * @param particle is the particle we are computed the direction for
  56879. */
  56880. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56881. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56882. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56883. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56884. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56885. direction.x += randX;
  56886. direction.y += randY;
  56887. direction.z += randZ;
  56888. direction.normalize();
  56889. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56890. };
  56891. /**
  56892. * Called by the particle System when the position is computed for the created particle.
  56893. * @param worldMatrix is the world matrix of the particle system
  56894. * @param positionToUpdate is the position vector to update with the result
  56895. * @param particle is the particle we are computed the position for
  56896. */
  56897. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56898. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56899. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56900. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56901. var theta = Math.acos(2 * v - 1);
  56902. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56903. var randY = randRadius * Math.cos(theta);
  56904. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56905. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56906. };
  56907. /**
  56908. * Clones the current emitter and returns a copy of it
  56909. * @returns the new emitter
  56910. */
  56911. SphereParticleEmitter.prototype.clone = function () {
  56912. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56913. BABYLON.Tools.DeepCopy(this, newOne);
  56914. return newOne;
  56915. };
  56916. /**
  56917. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56918. * @param effect defines the update shader
  56919. */
  56920. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56921. effect.setFloat("radius", this.radius);
  56922. effect.setFloat("radiusRange", this.radiusRange);
  56923. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56924. };
  56925. /**
  56926. * Returns a string to use to update the GPU particles update shader
  56927. * @returns a string containng the defines string
  56928. */
  56929. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56930. return "#define SPHEREEMITTER";
  56931. };
  56932. /**
  56933. * Returns the string "SphereParticleEmitter"
  56934. * @returns a string containing the class name
  56935. */
  56936. SphereParticleEmitter.prototype.getClassName = function () {
  56937. return "SphereParticleEmitter";
  56938. };
  56939. /**
  56940. * Serializes the particle system to a JSON object.
  56941. * @returns the JSON object
  56942. */
  56943. SphereParticleEmitter.prototype.serialize = function () {
  56944. var serializationObject = {};
  56945. serializationObject.type = this.getClassName();
  56946. serializationObject.radius = this.radius;
  56947. serializationObject.radiusRange = this.radiusRange;
  56948. serializationObject.directionRandomizer = this.directionRandomizer;
  56949. return serializationObject;
  56950. };
  56951. /**
  56952. * Parse properties from a JSON object
  56953. * @param serializationObject defines the JSON object
  56954. */
  56955. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56956. this.radius = serializationObject.radius;
  56957. this.radiusRange = serializationObject.radiusRange;
  56958. this.directionRandomizer = serializationObject.directionRandomizer;
  56959. };
  56960. return SphereParticleEmitter;
  56961. }());
  56962. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56963. /**
  56964. * Particle emitter emitting particles from the inside of a sphere.
  56965. * It emits the particles randomly between two vectors.
  56966. */
  56967. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56968. __extends(SphereDirectedParticleEmitter, _super);
  56969. /**
  56970. * Creates a new instance SphereDirectedParticleEmitter
  56971. * @param radius the radius of the emission sphere (1 by default)
  56972. * @param direction1 the min limit of the emission direction (up vector by default)
  56973. * @param direction2 the max limit of the emission direction (up vector by default)
  56974. */
  56975. function SphereDirectedParticleEmitter(radius,
  56976. /**
  56977. * The min limit of the emission direction.
  56978. */
  56979. direction1,
  56980. /**
  56981. * The max limit of the emission direction.
  56982. */
  56983. direction2) {
  56984. if (radius === void 0) { radius = 1; }
  56985. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56986. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56987. var _this = _super.call(this, radius) || this;
  56988. _this.direction1 = direction1;
  56989. _this.direction2 = direction2;
  56990. return _this;
  56991. }
  56992. /**
  56993. * Called by the particle System when the direction is computed for the created particle.
  56994. * @param worldMatrix is the world matrix of the particle system
  56995. * @param directionToUpdate is the direction vector to update with the result
  56996. * @param particle is the particle we are computed the direction for
  56997. */
  56998. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56999. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57000. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57001. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57002. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57003. };
  57004. /**
  57005. * Clones the current emitter and returns a copy of it
  57006. * @returns the new emitter
  57007. */
  57008. SphereDirectedParticleEmitter.prototype.clone = function () {
  57009. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57010. BABYLON.Tools.DeepCopy(this, newOne);
  57011. return newOne;
  57012. };
  57013. /**
  57014. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57015. * @param effect defines the update shader
  57016. */
  57017. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57018. effect.setFloat("radius", this.radius);
  57019. effect.setFloat("radiusRange", this.radiusRange);
  57020. effect.setVector3("direction1", this.direction1);
  57021. effect.setVector3("direction2", this.direction2);
  57022. };
  57023. /**
  57024. * Returns a string to use to update the GPU particles update shader
  57025. * @returns a string containng the defines string
  57026. */
  57027. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57028. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57029. };
  57030. /**
  57031. * Returns the string "SphereDirectedParticleEmitter"
  57032. * @returns a string containing the class name
  57033. */
  57034. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57035. return "SphereDirectedParticleEmitter";
  57036. };
  57037. /**
  57038. * Serializes the particle system to a JSON object.
  57039. * @returns the JSON object
  57040. */
  57041. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57042. var serializationObject = _super.prototype.serialize.call(this);
  57043. serializationObject.direction1 = this.direction1.asArray();
  57044. serializationObject.direction2 = this.direction2.asArray();
  57045. return serializationObject;
  57046. };
  57047. /**
  57048. * Parse properties from a JSON object
  57049. * @param serializationObject defines the JSON object
  57050. */
  57051. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57052. _super.prototype.parse.call(this, serializationObject);
  57053. this.direction1.copyFrom(serializationObject.direction1);
  57054. this.direction2.copyFrom(serializationObject.direction2);
  57055. };
  57056. return SphereDirectedParticleEmitter;
  57057. }(SphereParticleEmitter));
  57058. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57059. })(BABYLON || (BABYLON = {}));
  57060. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57061. var BABYLON;
  57062. (function (BABYLON) {
  57063. // Adds the parsers to the scene parsers.
  57064. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57065. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  57066. if (!individualParser) {
  57067. return;
  57068. }
  57069. // Particles Systems
  57070. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57071. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57072. var parsedParticleSystem = parsedData.particleSystems[index];
  57073. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  57074. }
  57075. }
  57076. });
  57077. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  57078. if (parsedParticleSystem.activeParticleCount) {
  57079. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57080. return ps;
  57081. }
  57082. else {
  57083. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57084. return ps;
  57085. }
  57086. });
  57087. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57088. if (uniformsNames === void 0) { uniformsNames = []; }
  57089. if (samplers === void 0) { samplers = []; }
  57090. if (defines === void 0) { defines = ""; }
  57091. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57092. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57093. if (defines.indexOf(" BILLBOARD") === -1) {
  57094. defines += "\n#define BILLBOARD\n";
  57095. }
  57096. if (samplers.indexOf("diffuseSampler") === -1) {
  57097. samplers.push("diffuseSampler");
  57098. }
  57099. return this.createEffect({
  57100. vertex: "particles",
  57101. fragmentElement: fragmentName
  57102. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57103. };
  57104. })(BABYLON || (BABYLON = {}));
  57105. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57106. var BABYLON;
  57107. (function (BABYLON) {
  57108. var ShaderMaterial = /** @class */ (function (_super) {
  57109. __extends(ShaderMaterial, _super);
  57110. function ShaderMaterial(name, scene, shaderPath, options) {
  57111. var _this = _super.call(this, name, scene) || this;
  57112. _this._textures = {};
  57113. _this._textureArrays = {};
  57114. _this._floats = {};
  57115. _this._ints = {};
  57116. _this._floatsArrays = {};
  57117. _this._colors3 = {};
  57118. _this._colors3Arrays = {};
  57119. _this._colors4 = {};
  57120. _this._vectors2 = {};
  57121. _this._vectors3 = {};
  57122. _this._vectors4 = {};
  57123. _this._matrices = {};
  57124. _this._matrices3x3 = {};
  57125. _this._matrices2x2 = {};
  57126. _this._vectors2Arrays = {};
  57127. _this._vectors3Arrays = {};
  57128. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  57129. _this._shaderPath = shaderPath;
  57130. options.needAlphaBlending = options.needAlphaBlending || false;
  57131. options.needAlphaTesting = options.needAlphaTesting || false;
  57132. options.attributes = options.attributes || ["position", "normal", "uv"];
  57133. options.uniforms = options.uniforms || ["worldViewProjection"];
  57134. options.uniformBuffers = options.uniformBuffers || [];
  57135. options.samplers = options.samplers || [];
  57136. options.defines = options.defines || [];
  57137. _this._options = options;
  57138. return _this;
  57139. }
  57140. ShaderMaterial.prototype.getClassName = function () {
  57141. return "ShaderMaterial";
  57142. };
  57143. ShaderMaterial.prototype.needAlphaBlending = function () {
  57144. return this._options.needAlphaBlending;
  57145. };
  57146. ShaderMaterial.prototype.needAlphaTesting = function () {
  57147. return this._options.needAlphaTesting;
  57148. };
  57149. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  57150. if (this._options.uniforms.indexOf(uniformName) === -1) {
  57151. this._options.uniforms.push(uniformName);
  57152. }
  57153. };
  57154. ShaderMaterial.prototype.setTexture = function (name, texture) {
  57155. if (this._options.samplers.indexOf(name) === -1) {
  57156. this._options.samplers.push(name);
  57157. }
  57158. this._textures[name] = texture;
  57159. return this;
  57160. };
  57161. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  57162. if (this._options.samplers.indexOf(name) === -1) {
  57163. this._options.samplers.push(name);
  57164. }
  57165. this._checkUniform(name);
  57166. this._textureArrays[name] = textures;
  57167. return this;
  57168. };
  57169. ShaderMaterial.prototype.setFloat = function (name, value) {
  57170. this._checkUniform(name);
  57171. this._floats[name] = value;
  57172. return this;
  57173. };
  57174. ShaderMaterial.prototype.setInt = function (name, value) {
  57175. this._checkUniform(name);
  57176. this._ints[name] = value;
  57177. return this;
  57178. };
  57179. ShaderMaterial.prototype.setFloats = function (name, value) {
  57180. this._checkUniform(name);
  57181. this._floatsArrays[name] = value;
  57182. return this;
  57183. };
  57184. ShaderMaterial.prototype.setColor3 = function (name, value) {
  57185. this._checkUniform(name);
  57186. this._colors3[name] = value;
  57187. return this;
  57188. };
  57189. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  57190. this._checkUniform(name);
  57191. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  57192. color.toArray(arr, arr.length);
  57193. return arr;
  57194. }, []);
  57195. return this;
  57196. };
  57197. ShaderMaterial.prototype.setColor4 = function (name, value) {
  57198. this._checkUniform(name);
  57199. this._colors4[name] = value;
  57200. return this;
  57201. };
  57202. ShaderMaterial.prototype.setVector2 = function (name, value) {
  57203. this._checkUniform(name);
  57204. this._vectors2[name] = value;
  57205. return this;
  57206. };
  57207. ShaderMaterial.prototype.setVector3 = function (name, value) {
  57208. this._checkUniform(name);
  57209. this._vectors3[name] = value;
  57210. return this;
  57211. };
  57212. ShaderMaterial.prototype.setVector4 = function (name, value) {
  57213. this._checkUniform(name);
  57214. this._vectors4[name] = value;
  57215. return this;
  57216. };
  57217. ShaderMaterial.prototype.setMatrix = function (name, value) {
  57218. this._checkUniform(name);
  57219. this._matrices[name] = value;
  57220. return this;
  57221. };
  57222. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  57223. this._checkUniform(name);
  57224. this._matrices3x3[name] = value;
  57225. return this;
  57226. };
  57227. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  57228. this._checkUniform(name);
  57229. this._matrices2x2[name] = value;
  57230. return this;
  57231. };
  57232. ShaderMaterial.prototype.setArray2 = function (name, value) {
  57233. this._checkUniform(name);
  57234. this._vectors2Arrays[name] = value;
  57235. return this;
  57236. };
  57237. ShaderMaterial.prototype.setArray3 = function (name, value) {
  57238. this._checkUniform(name);
  57239. this._vectors3Arrays[name] = value;
  57240. return this;
  57241. };
  57242. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  57243. if (!mesh) {
  57244. return true;
  57245. }
  57246. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  57247. return false;
  57248. }
  57249. return false;
  57250. };
  57251. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  57252. var scene = this.getScene();
  57253. var engine = scene.getEngine();
  57254. if (!this.checkReadyOnEveryCall) {
  57255. if (this._renderId === scene.getRenderId()) {
  57256. if (this._checkCache(scene, mesh, useInstances)) {
  57257. return true;
  57258. }
  57259. }
  57260. }
  57261. // Instances
  57262. var defines = [];
  57263. var attribs = [];
  57264. var fallbacks = new BABYLON.EffectFallbacks();
  57265. if (useInstances) {
  57266. defines.push("#define INSTANCES");
  57267. }
  57268. for (var index = 0; index < this._options.defines.length; index++) {
  57269. defines.push(this._options.defines[index]);
  57270. }
  57271. for (var index = 0; index < this._options.attributes.length; index++) {
  57272. attribs.push(this._options.attributes[index]);
  57273. }
  57274. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  57275. attribs.push(BABYLON.VertexBuffer.ColorKind);
  57276. defines.push("#define VERTEXCOLOR");
  57277. }
  57278. // Bones
  57279. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57282. if (mesh.numBoneInfluencers > 4) {
  57283. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57284. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57285. }
  57286. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57287. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  57288. fallbacks.addCPUSkinningFallback(0, mesh);
  57289. if (this._options.uniforms.indexOf("mBones") === -1) {
  57290. this._options.uniforms.push("mBones");
  57291. }
  57292. }
  57293. else {
  57294. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57295. }
  57296. // Textures
  57297. for (var name in this._textures) {
  57298. if (!this._textures[name].isReady()) {
  57299. return false;
  57300. }
  57301. }
  57302. // Alpha test
  57303. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  57304. defines.push("#define ALPHATEST");
  57305. }
  57306. var previousEffect = this._effect;
  57307. var join = defines.join("\n");
  57308. this._effect = engine.createEffect(this._shaderPath, {
  57309. attributes: attribs,
  57310. uniformsNames: this._options.uniforms,
  57311. uniformBuffersNames: this._options.uniformBuffers,
  57312. samplers: this._options.samplers,
  57313. defines: join,
  57314. fallbacks: fallbacks,
  57315. onCompiled: this.onCompiled,
  57316. onError: this.onError
  57317. }, engine);
  57318. if (!this._effect.isReady()) {
  57319. return false;
  57320. }
  57321. if (previousEffect !== this._effect) {
  57322. scene.resetCachedMaterial();
  57323. }
  57324. this._renderId = scene.getRenderId();
  57325. return true;
  57326. };
  57327. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  57328. var scene = this.getScene();
  57329. if (!this._effect) {
  57330. return;
  57331. }
  57332. if (this._options.uniforms.indexOf("world") !== -1) {
  57333. this._effect.setMatrix("world", world);
  57334. }
  57335. if (this._options.uniforms.indexOf("worldView") !== -1) {
  57336. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  57337. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  57338. }
  57339. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  57340. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  57341. }
  57342. };
  57343. ShaderMaterial.prototype.bind = function (world, mesh) {
  57344. // Std values
  57345. this.bindOnlyWorldMatrix(world);
  57346. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  57347. if (this._options.uniforms.indexOf("view") !== -1) {
  57348. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  57349. }
  57350. if (this._options.uniforms.indexOf("projection") !== -1) {
  57351. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  57352. }
  57353. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  57354. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  57355. }
  57356. // Bones
  57357. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  57358. var name;
  57359. // Texture
  57360. for (name in this._textures) {
  57361. this._effect.setTexture(name, this._textures[name]);
  57362. }
  57363. // Texture arrays
  57364. for (name in this._textureArrays) {
  57365. this._effect.setTextureArray(name, this._textureArrays[name]);
  57366. }
  57367. // Int
  57368. for (name in this._ints) {
  57369. this._effect.setInt(name, this._ints[name]);
  57370. }
  57371. // Float
  57372. for (name in this._floats) {
  57373. this._effect.setFloat(name, this._floats[name]);
  57374. }
  57375. // Floats
  57376. for (name in this._floatsArrays) {
  57377. this._effect.setArray(name, this._floatsArrays[name]);
  57378. }
  57379. // Color3
  57380. for (name in this._colors3) {
  57381. this._effect.setColor3(name, this._colors3[name]);
  57382. }
  57383. for (name in this._colors3Arrays) {
  57384. this._effect.setArray3(name, this._colors3Arrays[name]);
  57385. }
  57386. // Color4
  57387. for (name in this._colors4) {
  57388. var color = this._colors4[name];
  57389. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57390. }
  57391. // Vector2
  57392. for (name in this._vectors2) {
  57393. this._effect.setVector2(name, this._vectors2[name]);
  57394. }
  57395. // Vector3
  57396. for (name in this._vectors3) {
  57397. this._effect.setVector3(name, this._vectors3[name]);
  57398. }
  57399. // Vector4
  57400. for (name in this._vectors4) {
  57401. this._effect.setVector4(name, this._vectors4[name]);
  57402. }
  57403. // Matrix
  57404. for (name in this._matrices) {
  57405. this._effect.setMatrix(name, this._matrices[name]);
  57406. }
  57407. // Matrix 3x3
  57408. for (name in this._matrices3x3) {
  57409. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  57410. }
  57411. // Matrix 2x2
  57412. for (name in this._matrices2x2) {
  57413. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  57414. }
  57415. // Vector2Array
  57416. for (name in this._vectors2Arrays) {
  57417. this._effect.setArray2(name, this._vectors2Arrays[name]);
  57418. }
  57419. // Vector3Array
  57420. for (name in this._vectors3Arrays) {
  57421. this._effect.setArray3(name, this._vectors3Arrays[name]);
  57422. }
  57423. }
  57424. this._afterBind(mesh);
  57425. };
  57426. ShaderMaterial.prototype.getActiveTextures = function () {
  57427. var activeTextures = _super.prototype.getActiveTextures.call(this);
  57428. for (var name in this._textures) {
  57429. activeTextures.push(this._textures[name]);
  57430. }
  57431. for (var name in this._textureArrays) {
  57432. var array = this._textureArrays[name];
  57433. for (var index = 0; index < array.length; index++) {
  57434. activeTextures.push(array[index]);
  57435. }
  57436. }
  57437. return activeTextures;
  57438. };
  57439. ShaderMaterial.prototype.hasTexture = function (texture) {
  57440. if (_super.prototype.hasTexture.call(this, texture)) {
  57441. return true;
  57442. }
  57443. for (var name in this._textures) {
  57444. if (this._textures[name] === texture) {
  57445. return true;
  57446. }
  57447. }
  57448. for (var name in this._textureArrays) {
  57449. var array = this._textureArrays[name];
  57450. for (var index = 0; index < array.length; index++) {
  57451. if (array[index] === texture) {
  57452. return true;
  57453. }
  57454. }
  57455. }
  57456. return false;
  57457. };
  57458. ShaderMaterial.prototype.clone = function (name) {
  57459. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  57460. return newShaderMaterial;
  57461. };
  57462. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  57463. if (forceDisposeTextures) {
  57464. var name;
  57465. for (name in this._textures) {
  57466. this._textures[name].dispose();
  57467. }
  57468. for (name in this._textureArrays) {
  57469. var array = this._textureArrays[name];
  57470. for (var index = 0; index < array.length; index++) {
  57471. array[index].dispose();
  57472. }
  57473. }
  57474. }
  57475. this._textures = {};
  57476. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  57477. };
  57478. ShaderMaterial.prototype.serialize = function () {
  57479. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  57480. serializationObject.customType = "BABYLON.ShaderMaterial";
  57481. serializationObject.options = this._options;
  57482. serializationObject.shaderPath = this._shaderPath;
  57483. var name;
  57484. // Texture
  57485. serializationObject.textures = {};
  57486. for (name in this._textures) {
  57487. serializationObject.textures[name] = this._textures[name].serialize();
  57488. }
  57489. // Texture arrays
  57490. serializationObject.textureArrays = {};
  57491. for (name in this._textureArrays) {
  57492. serializationObject.textureArrays[name] = [];
  57493. var array = this._textureArrays[name];
  57494. for (var index = 0; index < array.length; index++) {
  57495. serializationObject.textureArrays[name].push(array[index].serialize());
  57496. }
  57497. }
  57498. // Float
  57499. serializationObject.floats = {};
  57500. for (name in this._floats) {
  57501. serializationObject.floats[name] = this._floats[name];
  57502. }
  57503. // Float s
  57504. serializationObject.FloatArrays = {};
  57505. for (name in this._floatsArrays) {
  57506. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  57507. }
  57508. // Color3
  57509. serializationObject.colors3 = {};
  57510. for (name in this._colors3) {
  57511. serializationObject.colors3[name] = this._colors3[name].asArray();
  57512. }
  57513. // Color3 array
  57514. serializationObject.colors3Arrays = {};
  57515. for (name in this._colors3Arrays) {
  57516. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  57517. }
  57518. // Color4
  57519. serializationObject.colors4 = {};
  57520. for (name in this._colors4) {
  57521. serializationObject.colors4[name] = this._colors4[name].asArray();
  57522. }
  57523. // Vector2
  57524. serializationObject.vectors2 = {};
  57525. for (name in this._vectors2) {
  57526. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  57527. }
  57528. // Vector3
  57529. serializationObject.vectors3 = {};
  57530. for (name in this._vectors3) {
  57531. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  57532. }
  57533. // Vector4
  57534. serializationObject.vectors4 = {};
  57535. for (name in this._vectors4) {
  57536. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  57537. }
  57538. // Matrix
  57539. serializationObject.matrices = {};
  57540. for (name in this._matrices) {
  57541. serializationObject.matrices[name] = this._matrices[name].asArray();
  57542. }
  57543. // Matrix 3x3
  57544. serializationObject.matrices3x3 = {};
  57545. for (name in this._matrices3x3) {
  57546. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  57547. }
  57548. // Matrix 2x2
  57549. serializationObject.matrices2x2 = {};
  57550. for (name in this._matrices2x2) {
  57551. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  57552. }
  57553. // Vector2Array
  57554. serializationObject.vectors2Arrays = {};
  57555. for (name in this._vectors2Arrays) {
  57556. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  57557. }
  57558. // Vector3Array
  57559. serializationObject.vectors3Arrays = {};
  57560. for (name in this._vectors3Arrays) {
  57561. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  57562. }
  57563. return serializationObject;
  57564. };
  57565. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  57566. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  57567. var name;
  57568. // Texture
  57569. for (name in source.textures) {
  57570. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  57571. }
  57572. // Texture arrays
  57573. for (name in source.textureArrays) {
  57574. var array = source.textureArrays[name];
  57575. var textureArray = new Array();
  57576. for (var index = 0; index < array.length; index++) {
  57577. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  57578. }
  57579. material.setTextureArray(name, textureArray);
  57580. }
  57581. // Float
  57582. for (name in source.floats) {
  57583. material.setFloat(name, source.floats[name]);
  57584. }
  57585. // Float s
  57586. for (name in source.floatsArrays) {
  57587. material.setFloats(name, source.floatsArrays[name]);
  57588. }
  57589. // Color3
  57590. for (name in source.colors3) {
  57591. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  57592. }
  57593. // Color3 arrays
  57594. for (name in source.colors3Arrays) {
  57595. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  57596. if (i % 3 === 0) {
  57597. arr.push([num]);
  57598. }
  57599. else {
  57600. arr[arr.length - 1].push(num);
  57601. }
  57602. return arr;
  57603. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  57604. material.setColor3Array(name, colors);
  57605. }
  57606. // Color4
  57607. for (name in source.colors4) {
  57608. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  57609. }
  57610. // Vector2
  57611. for (name in source.vectors2) {
  57612. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  57613. }
  57614. // Vector3
  57615. for (name in source.vectors3) {
  57616. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  57617. }
  57618. // Vector4
  57619. for (name in source.vectors4) {
  57620. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  57621. }
  57622. // Matrix
  57623. for (name in source.matrices) {
  57624. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  57625. }
  57626. // Matrix 3x3
  57627. for (name in source.matrices3x3) {
  57628. material.setMatrix3x3(name, source.matrices3x3[name]);
  57629. }
  57630. // Matrix 2x2
  57631. for (name in source.matrices2x2) {
  57632. material.setMatrix2x2(name, source.matrices2x2[name]);
  57633. }
  57634. // Vector2Array
  57635. for (name in source.vectors2Arrays) {
  57636. material.setArray2(name, source.vectors2Arrays[name]);
  57637. }
  57638. // Vector3Array
  57639. for (name in source.vectors3Arrays) {
  57640. material.setArray3(name, source.vectors3Arrays[name]);
  57641. }
  57642. return material;
  57643. };
  57644. return ShaderMaterial;
  57645. }(BABYLON.Material));
  57646. BABYLON.ShaderMaterial = ShaderMaterial;
  57647. })(BABYLON || (BABYLON = {}));
  57648. //# sourceMappingURL=babylon.shaderMaterial.js.map
  57649. var BABYLON;
  57650. (function (BABYLON) {
  57651. var GroundMesh = /** @class */ (function (_super) {
  57652. __extends(GroundMesh, _super);
  57653. function GroundMesh(name, scene) {
  57654. var _this = _super.call(this, name, scene) || this;
  57655. _this.generateOctree = false;
  57656. return _this;
  57657. }
  57658. GroundMesh.prototype.getClassName = function () {
  57659. return "GroundMesh";
  57660. };
  57661. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  57662. get: function () {
  57663. return Math.min(this._subdivisionsX, this._subdivisionsY);
  57664. },
  57665. enumerable: true,
  57666. configurable: true
  57667. });
  57668. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  57669. get: function () {
  57670. return this._subdivisionsX;
  57671. },
  57672. enumerable: true,
  57673. configurable: true
  57674. });
  57675. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  57676. get: function () {
  57677. return this._subdivisionsY;
  57678. },
  57679. enumerable: true,
  57680. configurable: true
  57681. });
  57682. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  57683. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  57684. this._subdivisionsX = chunksCount;
  57685. this._subdivisionsY = chunksCount;
  57686. this.subdivide(chunksCount);
  57687. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  57688. };
  57689. /**
  57690. * Returns a height (y) value in the Worl system :
  57691. * the ground altitude at the coordinates (x, z) expressed in the World system.
  57692. * Returns the ground y position if (x, z) are outside the ground surface.
  57693. */
  57694. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  57695. var world = this.getWorldMatrix();
  57696. var invMat = BABYLON.Tmp.Matrix[5];
  57697. world.invertToRef(invMat);
  57698. var tmpVect = BABYLON.Tmp.Vector3[8];
  57699. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  57700. x = tmpVect.x;
  57701. z = tmpVect.z;
  57702. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57703. return this.position.y;
  57704. }
  57705. if (!this._heightQuads || this._heightQuads.length == 0) {
  57706. this._initHeightQuads();
  57707. this._computeHeightQuads();
  57708. }
  57709. var facet = this._getFacetAt(x, z);
  57710. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  57711. // return y in the World system
  57712. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  57713. return tmpVect.y;
  57714. };
  57715. /**
  57716. * Returns a normalized vector (Vector3) orthogonal to the ground
  57717. * at the ground coordinates (x, z) expressed in the World system.
  57718. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  57719. */
  57720. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  57721. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  57722. this.getNormalAtCoordinatesToRef(x, z, normal);
  57723. return normal;
  57724. };
  57725. /**
  57726. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  57727. * at the ground coordinates (x, z) expressed in the World system.
  57728. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  57729. * Returns the GroundMesh.
  57730. */
  57731. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  57732. var world = this.getWorldMatrix();
  57733. var tmpMat = BABYLON.Tmp.Matrix[5];
  57734. world.invertToRef(tmpMat);
  57735. var tmpVect = BABYLON.Tmp.Vector3[8];
  57736. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  57737. x = tmpVect.x;
  57738. z = tmpVect.z;
  57739. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  57740. return this;
  57741. }
  57742. if (!this._heightQuads || this._heightQuads.length == 0) {
  57743. this._initHeightQuads();
  57744. this._computeHeightQuads();
  57745. }
  57746. var facet = this._getFacetAt(x, z);
  57747. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  57748. return this;
  57749. };
  57750. /**
  57751. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  57752. * if the ground has been updated.
  57753. * This can be used in the render loop.
  57754. * Returns the GroundMesh.
  57755. */
  57756. GroundMesh.prototype.updateCoordinateHeights = function () {
  57757. if (!this._heightQuads || this._heightQuads.length == 0) {
  57758. this._initHeightQuads();
  57759. }
  57760. this._computeHeightQuads();
  57761. return this;
  57762. };
  57763. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  57764. GroundMesh.prototype._getFacetAt = function (x, z) {
  57765. // retrieve col and row from x, z coordinates in the ground local system
  57766. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  57767. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  57768. var quad = this._heightQuads[row * this._subdivisionsX + col];
  57769. var facet;
  57770. if (z < quad.slope.x * x + quad.slope.y) {
  57771. facet = quad.facet1;
  57772. }
  57773. else {
  57774. facet = quad.facet2;
  57775. }
  57776. return facet;
  57777. };
  57778. // Creates and populates the heightMap array with "facet" elements :
  57779. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  57780. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57781. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57782. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57783. // Returns the GroundMesh.
  57784. GroundMesh.prototype._initHeightQuads = function () {
  57785. var subdivisionsX = this._subdivisionsX;
  57786. var subdivisionsY = this._subdivisionsY;
  57787. this._heightQuads = new Array();
  57788. for (var row = 0; row < subdivisionsY; row++) {
  57789. for (var col = 0; col < subdivisionsX; col++) {
  57790. 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) };
  57791. this._heightQuads[row * subdivisionsX + col] = quad;
  57792. }
  57793. }
  57794. return this;
  57795. };
  57796. // Compute each quad element values and update the the heightMap array :
  57797. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  57798. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  57799. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  57800. // Returns the GroundMesh.
  57801. GroundMesh.prototype._computeHeightQuads = function () {
  57802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57803. if (!positions) {
  57804. return this;
  57805. }
  57806. var v1 = BABYLON.Tmp.Vector3[3];
  57807. var v2 = BABYLON.Tmp.Vector3[2];
  57808. var v3 = BABYLON.Tmp.Vector3[1];
  57809. var v4 = BABYLON.Tmp.Vector3[0];
  57810. var v1v2 = BABYLON.Tmp.Vector3[4];
  57811. var v1v3 = BABYLON.Tmp.Vector3[5];
  57812. var v1v4 = BABYLON.Tmp.Vector3[6];
  57813. var norm1 = BABYLON.Tmp.Vector3[7];
  57814. var norm2 = BABYLON.Tmp.Vector3[8];
  57815. var i = 0;
  57816. var j = 0;
  57817. var k = 0;
  57818. var cd = 0; // 2D slope coefficient : z = cd * x + h
  57819. var h = 0;
  57820. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  57821. var d2 = 0;
  57822. var subdivisionsX = this._subdivisionsX;
  57823. var subdivisionsY = this._subdivisionsY;
  57824. for (var row = 0; row < subdivisionsY; row++) {
  57825. for (var col = 0; col < subdivisionsX; col++) {
  57826. i = col * 3;
  57827. j = row * (subdivisionsX + 1) * 3;
  57828. k = (row + 1) * (subdivisionsX + 1) * 3;
  57829. v1.x = positions[j + i];
  57830. v1.y = positions[j + i + 1];
  57831. v1.z = positions[j + i + 2];
  57832. v2.x = positions[j + i + 3];
  57833. v2.y = positions[j + i + 4];
  57834. v2.z = positions[j + i + 5];
  57835. v3.x = positions[k + i];
  57836. v3.y = positions[k + i + 1];
  57837. v3.z = positions[k + i + 2];
  57838. v4.x = positions[k + i + 3];
  57839. v4.y = positions[k + i + 4];
  57840. v4.z = positions[k + i + 5];
  57841. // 2D slope V1V4
  57842. cd = (v4.z - v1.z) / (v4.x - v1.x);
  57843. h = v1.z - cd * v1.x; // v1 belongs to the slope
  57844. // facet equations :
  57845. // we compute each facet normal vector
  57846. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  57847. // we compute the value d by applying the equation to v1 which belongs to the plane
  57848. // then we store the facet equation in a Vector4
  57849. v2.subtractToRef(v1, v1v2);
  57850. v3.subtractToRef(v1, v1v3);
  57851. v4.subtractToRef(v1, v1v4);
  57852. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  57853. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  57854. norm1.normalize();
  57855. norm2.normalize();
  57856. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  57857. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  57858. var quad = this._heightQuads[row * subdivisionsX + col];
  57859. quad.slope.copyFromFloats(cd, h);
  57860. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  57861. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  57862. }
  57863. }
  57864. return this;
  57865. };
  57866. GroundMesh.prototype.serialize = function (serializationObject) {
  57867. _super.prototype.serialize.call(this, serializationObject);
  57868. serializationObject.subdivisionsX = this._subdivisionsX;
  57869. serializationObject.subdivisionsY = this._subdivisionsY;
  57870. serializationObject.minX = this._minX;
  57871. serializationObject.maxX = this._maxX;
  57872. serializationObject.minZ = this._minZ;
  57873. serializationObject.maxZ = this._maxZ;
  57874. serializationObject.width = this._width;
  57875. serializationObject.height = this._height;
  57876. };
  57877. GroundMesh.Parse = function (parsedMesh, scene) {
  57878. var result = new GroundMesh(parsedMesh.name, scene);
  57879. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  57880. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  57881. result._minX = parsedMesh.minX;
  57882. result._maxX = parsedMesh.maxX;
  57883. result._minZ = parsedMesh.minZ;
  57884. result._maxZ = parsedMesh.maxZ;
  57885. result._width = parsedMesh.width;
  57886. result._height = parsedMesh.height;
  57887. return result;
  57888. };
  57889. return GroundMesh;
  57890. }(BABYLON.Mesh));
  57891. BABYLON.GroundMesh = GroundMesh;
  57892. })(BABYLON || (BABYLON = {}));
  57893. //# sourceMappingURL=babylon.groundMesh.js.map
  57894. var BABYLON;
  57895. (function (BABYLON) {
  57896. /**
  57897. * Creates an instance based on a source mesh.
  57898. */
  57899. var InstancedMesh = /** @class */ (function (_super) {
  57900. __extends(InstancedMesh, _super);
  57901. function InstancedMesh(name, source) {
  57902. var _this = _super.call(this, name, source.getScene()) || this;
  57903. source.instances.push(_this);
  57904. _this._sourceMesh = source;
  57905. _this.position.copyFrom(source.position);
  57906. _this.rotation.copyFrom(source.rotation);
  57907. _this.scaling.copyFrom(source.scaling);
  57908. if (source.rotationQuaternion) {
  57909. _this.rotationQuaternion = source.rotationQuaternion.clone();
  57910. }
  57911. _this.infiniteDistance = source.infiniteDistance;
  57912. _this.setPivotMatrix(source.getPivotMatrix());
  57913. _this.refreshBoundingInfo();
  57914. _this._syncSubMeshes();
  57915. return _this;
  57916. }
  57917. /**
  57918. * Returns the string "InstancedMesh".
  57919. */
  57920. InstancedMesh.prototype.getClassName = function () {
  57921. return "InstancedMesh";
  57922. };
  57923. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  57924. // Methods
  57925. get: function () {
  57926. return this._sourceMesh.receiveShadows;
  57927. },
  57928. enumerable: true,
  57929. configurable: true
  57930. });
  57931. Object.defineProperty(InstancedMesh.prototype, "material", {
  57932. get: function () {
  57933. return this._sourceMesh.material;
  57934. },
  57935. enumerable: true,
  57936. configurable: true
  57937. });
  57938. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  57939. get: function () {
  57940. return this._sourceMesh.visibility;
  57941. },
  57942. enumerable: true,
  57943. configurable: true
  57944. });
  57945. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  57946. get: function () {
  57947. return this._sourceMesh.skeleton;
  57948. },
  57949. enumerable: true,
  57950. configurable: true
  57951. });
  57952. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  57953. get: function () {
  57954. return this._sourceMesh.renderingGroupId;
  57955. },
  57956. set: function (value) {
  57957. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  57958. return;
  57959. }
  57960. //no-op with warning
  57961. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  57962. },
  57963. enumerable: true,
  57964. configurable: true
  57965. });
  57966. /**
  57967. * Returns the total number of vertices (integer).
  57968. */
  57969. InstancedMesh.prototype.getTotalVertices = function () {
  57970. return this._sourceMesh.getTotalVertices();
  57971. };
  57972. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  57973. get: function () {
  57974. return this._sourceMesh;
  57975. },
  57976. enumerable: true,
  57977. configurable: true
  57978. });
  57979. /**
  57980. * Is this node ready to be used/rendered
  57981. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  57982. * @return {boolean} is it ready
  57983. */
  57984. InstancedMesh.prototype.isReady = function (completeCheck) {
  57985. if (completeCheck === void 0) { completeCheck = false; }
  57986. return this._sourceMesh.isReady(completeCheck, true);
  57987. };
  57988. /**
  57989. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  57990. */
  57991. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  57992. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  57993. };
  57994. /**
  57995. * Sets the vertex data of the mesh geometry for the requested `kind`.
  57996. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  57997. * The `data` are either a numeric array either a Float32Array.
  57998. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  57999. * 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).
  58000. * Note that a new underlying VertexBuffer object is created each call.
  58001. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  58002. *
  58003. * Possible `kind` values :
  58004. * - BABYLON.VertexBuffer.PositionKind
  58005. * - BABYLON.VertexBuffer.UVKind
  58006. * - BABYLON.VertexBuffer.UV2Kind
  58007. * - BABYLON.VertexBuffer.UV3Kind
  58008. * - BABYLON.VertexBuffer.UV4Kind
  58009. * - BABYLON.VertexBuffer.UV5Kind
  58010. * - BABYLON.VertexBuffer.UV6Kind
  58011. * - BABYLON.VertexBuffer.ColorKind
  58012. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58013. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58014. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58015. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58016. *
  58017. * Returns the Mesh.
  58018. */
  58019. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  58020. if (this.sourceMesh) {
  58021. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  58022. }
  58023. return this.sourceMesh;
  58024. };
  58025. /**
  58026. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  58027. * If the mesh has no geometry, it is simply returned as it is.
  58028. * The `data` are either a numeric array either a Float32Array.
  58029. * No new underlying VertexBuffer object is created.
  58030. * 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.
  58031. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  58032. *
  58033. * Possible `kind` values :
  58034. * - BABYLON.VertexBuffer.PositionKind
  58035. * - BABYLON.VertexBuffer.UVKind
  58036. * - BABYLON.VertexBuffer.UV2Kind
  58037. * - BABYLON.VertexBuffer.UV3Kind
  58038. * - BABYLON.VertexBuffer.UV4Kind
  58039. * - BABYLON.VertexBuffer.UV5Kind
  58040. * - BABYLON.VertexBuffer.UV6Kind
  58041. * - BABYLON.VertexBuffer.ColorKind
  58042. * - BABYLON.VertexBuffer.MatricesIndicesKind
  58043. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  58044. * - BABYLON.VertexBuffer.MatricesWeightsKind
  58045. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  58046. *
  58047. * Returns the Mesh.
  58048. */
  58049. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  58050. if (this.sourceMesh) {
  58051. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  58052. }
  58053. return this.sourceMesh;
  58054. };
  58055. /**
  58056. * Sets the mesh indices.
  58057. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  58058. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  58059. * This method creates a new index buffer each call.
  58060. * Returns the Mesh.
  58061. */
  58062. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  58063. if (totalVertices === void 0) { totalVertices = null; }
  58064. if (this.sourceMesh) {
  58065. this.sourceMesh.setIndices(indices, totalVertices);
  58066. }
  58067. return this.sourceMesh;
  58068. };
  58069. /**
  58070. * Boolean : True if the mesh owns the requested kind of data.
  58071. */
  58072. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  58073. return this._sourceMesh.isVerticesDataPresent(kind);
  58074. };
  58075. /**
  58076. * Returns an array of indices (IndicesArray).
  58077. */
  58078. InstancedMesh.prototype.getIndices = function () {
  58079. return this._sourceMesh.getIndices();
  58080. };
  58081. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  58082. get: function () {
  58083. return this._sourceMesh._positions;
  58084. },
  58085. enumerable: true,
  58086. configurable: true
  58087. });
  58088. /**
  58089. * Sets a new updated BoundingInfo to the mesh.
  58090. * Returns the mesh.
  58091. */
  58092. InstancedMesh.prototype.refreshBoundingInfo = function () {
  58093. var meshBB = this._sourceMesh.getBoundingInfo();
  58094. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  58095. this._updateBoundingInfo();
  58096. return this;
  58097. };
  58098. InstancedMesh.prototype._preActivate = function () {
  58099. if (this._currentLOD) {
  58100. this._currentLOD._preActivate();
  58101. }
  58102. return this;
  58103. };
  58104. InstancedMesh.prototype._activate = function (renderId) {
  58105. if (this._currentLOD) {
  58106. this._currentLOD._registerInstanceForRenderId(this, renderId);
  58107. }
  58108. return this;
  58109. };
  58110. /**
  58111. * Returns the current associated LOD AbstractMesh.
  58112. */
  58113. InstancedMesh.prototype.getLOD = function (camera) {
  58114. if (!camera) {
  58115. return this;
  58116. }
  58117. var boundingInfo = this.getBoundingInfo();
  58118. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  58119. if (this._currentLOD === this.sourceMesh) {
  58120. return this;
  58121. }
  58122. return this._currentLOD;
  58123. };
  58124. InstancedMesh.prototype._syncSubMeshes = function () {
  58125. this.releaseSubMeshes();
  58126. if (this._sourceMesh.subMeshes) {
  58127. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  58128. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  58129. }
  58130. }
  58131. return this;
  58132. };
  58133. InstancedMesh.prototype._generatePointsArray = function () {
  58134. return this._sourceMesh._generatePointsArray();
  58135. };
  58136. /**
  58137. * Creates a new InstancedMesh from the current mesh.
  58138. * - name (string) : the cloned mesh name
  58139. * - newParent (optional Node) : the optional Node to parent the clone to.
  58140. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  58141. *
  58142. * Returns the clone.
  58143. */
  58144. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58145. var result = this._sourceMesh.createInstance(name);
  58146. // Deep copy
  58147. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  58148. // Bounding info
  58149. this.refreshBoundingInfo();
  58150. // Parent
  58151. if (newParent) {
  58152. result.parent = newParent;
  58153. }
  58154. if (!doNotCloneChildren) {
  58155. // Children
  58156. for (var index = 0; index < this.getScene().meshes.length; index++) {
  58157. var mesh = this.getScene().meshes[index];
  58158. if (mesh.parent === this) {
  58159. mesh.clone(mesh.name, result);
  58160. }
  58161. }
  58162. }
  58163. result.computeWorldMatrix(true);
  58164. return result;
  58165. };
  58166. /**
  58167. * Disposes the InstancedMesh.
  58168. * Returns nothing.
  58169. */
  58170. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  58171. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  58172. // Remove from mesh
  58173. var index = this._sourceMesh.instances.indexOf(this);
  58174. this._sourceMesh.instances.splice(index, 1);
  58175. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  58176. };
  58177. return InstancedMesh;
  58178. }(BABYLON.AbstractMesh));
  58179. BABYLON.InstancedMesh = InstancedMesh;
  58180. })(BABYLON || (BABYLON = {}));
  58181. //# sourceMappingURL=babylon.instancedMesh.js.map
  58182. var BABYLON;
  58183. (function (BABYLON) {
  58184. var LinesMesh = /** @class */ (function (_super) {
  58185. __extends(LinesMesh, _super);
  58186. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  58187. if (scene === void 0) { scene = null; }
  58188. if (parent === void 0) { parent = null; }
  58189. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  58190. _this.useVertexColor = useVertexColor;
  58191. _this.useVertexAlpha = useVertexAlpha;
  58192. _this.color = new BABYLON.Color3(1, 1, 1);
  58193. _this.alpha = 1;
  58194. if (source) {
  58195. _this.color = source.color.clone();
  58196. _this.alpha = source.alpha;
  58197. _this.useVertexColor = source.useVertexColor;
  58198. _this.useVertexAlpha = source.useVertexAlpha;
  58199. }
  58200. _this._intersectionThreshold = 0.1;
  58201. var defines = [];
  58202. var options = {
  58203. attributes: [BABYLON.VertexBuffer.PositionKind],
  58204. uniforms: ["world", "viewProjection"],
  58205. needAlphaBlending: true,
  58206. defines: defines
  58207. };
  58208. if (useVertexAlpha === false) {
  58209. options.needAlphaBlending = false;
  58210. }
  58211. if (!useVertexColor) {
  58212. options.uniforms.push("color");
  58213. }
  58214. else {
  58215. options.defines.push("#define VERTEXCOLOR");
  58216. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  58217. }
  58218. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  58219. return _this;
  58220. }
  58221. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  58222. /**
  58223. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58224. * This margin is expressed in world space coordinates, so its value may vary.
  58225. * Default value is 0.1
  58226. * @returns the intersection Threshold value.
  58227. */
  58228. get: function () {
  58229. return this._intersectionThreshold;
  58230. },
  58231. /**
  58232. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  58233. * This margin is expressed in world space coordinates, so its value may vary.
  58234. * @param value the new threshold to apply
  58235. */
  58236. set: function (value) {
  58237. if (this._intersectionThreshold === value) {
  58238. return;
  58239. }
  58240. this._intersectionThreshold = value;
  58241. if (this.geometry) {
  58242. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  58243. }
  58244. },
  58245. enumerable: true,
  58246. configurable: true
  58247. });
  58248. /**
  58249. * Returns the string "LineMesh"
  58250. */
  58251. LinesMesh.prototype.getClassName = function () {
  58252. return "LinesMesh";
  58253. };
  58254. Object.defineProperty(LinesMesh.prototype, "material", {
  58255. /**
  58256. * @hidden
  58257. */
  58258. get: function () {
  58259. return this._colorShader;
  58260. },
  58261. /**
  58262. * @hidden
  58263. */
  58264. set: function (value) {
  58265. // Do nothing
  58266. },
  58267. enumerable: true,
  58268. configurable: true
  58269. });
  58270. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  58271. /**
  58272. * @hidden
  58273. */
  58274. get: function () {
  58275. return false;
  58276. },
  58277. enumerable: true,
  58278. configurable: true
  58279. });
  58280. LinesMesh.prototype.createInstance = function (name) {
  58281. throw new Error("LinesMeshes do not support createInstance.");
  58282. };
  58283. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  58284. if (!this._geometry) {
  58285. return this;
  58286. }
  58287. // VBOs
  58288. this._geometry._bind(this._colorShader.getEffect());
  58289. // Color
  58290. if (!this.useVertexColor) {
  58291. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  58292. }
  58293. return this;
  58294. };
  58295. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  58296. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  58297. return this;
  58298. }
  58299. var engine = this.getScene().getEngine();
  58300. // Draw order
  58301. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  58302. return this;
  58303. };
  58304. LinesMesh.prototype.dispose = function (doNotRecurse) {
  58305. this._colorShader.dispose();
  58306. _super.prototype.dispose.call(this, doNotRecurse);
  58307. };
  58308. /**
  58309. * Returns a new LineMesh object cloned from the current one.
  58310. */
  58311. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  58312. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  58313. };
  58314. return LinesMesh;
  58315. }(BABYLON.Mesh));
  58316. BABYLON.LinesMesh = LinesMesh;
  58317. })(BABYLON || (BABYLON = {}));
  58318. //# sourceMappingURL=babylon.linesMesh.js.map
  58319. var BABYLON;
  58320. (function (BABYLON) {
  58321. /**
  58322. * This class implement a typical dictionary using a string as key and the generic type T as value.
  58323. * The underlying implementation relies on an associative array to ensure the best performances.
  58324. * The value can be anything including 'null' but except 'undefined'
  58325. */
  58326. var StringDictionary = /** @class */ (function () {
  58327. function StringDictionary() {
  58328. this._count = 0;
  58329. this._data = {};
  58330. }
  58331. /**
  58332. * This will clear this dictionary and copy the content from the 'source' one.
  58333. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  58334. * @param source the dictionary to take the content from and copy to this dictionary
  58335. */
  58336. StringDictionary.prototype.copyFrom = function (source) {
  58337. var _this = this;
  58338. this.clear();
  58339. source.forEach(function (t, v) { return _this.add(t, v); });
  58340. };
  58341. /**
  58342. * Get a value based from its key
  58343. * @param key the given key to get the matching value from
  58344. * @return the value if found, otherwise undefined is returned
  58345. */
  58346. StringDictionary.prototype.get = function (key) {
  58347. var val = this._data[key];
  58348. if (val !== undefined) {
  58349. return val;
  58350. }
  58351. return undefined;
  58352. };
  58353. /**
  58354. * Get a value from its key or add it if it doesn't exist.
  58355. * This method will ensure you that a given key/data will be present in the dictionary.
  58356. * @param key the given key to get the matching value from
  58357. * @param factory the factory that will create the value if the key is not present in the dictionary.
  58358. * The factory will only be invoked if there's no data for the given key.
  58359. * @return the value corresponding to the key.
  58360. */
  58361. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  58362. var val = this.get(key);
  58363. if (val !== undefined) {
  58364. return val;
  58365. }
  58366. val = factory(key);
  58367. if (val) {
  58368. this.add(key, val);
  58369. }
  58370. return val;
  58371. };
  58372. /**
  58373. * Get a value from its key if present in the dictionary otherwise add it
  58374. * @param key the key to get the value from
  58375. * @param val if there's no such key/value pair in the dictionary add it with this value
  58376. * @return the value corresponding to the key
  58377. */
  58378. StringDictionary.prototype.getOrAdd = function (key, val) {
  58379. var curVal = this.get(key);
  58380. if (curVal !== undefined) {
  58381. return curVal;
  58382. }
  58383. this.add(key, val);
  58384. return val;
  58385. };
  58386. /**
  58387. * Check if there's a given key in the dictionary
  58388. * @param key the key to check for
  58389. * @return true if the key is present, false otherwise
  58390. */
  58391. StringDictionary.prototype.contains = function (key) {
  58392. return this._data[key] !== undefined;
  58393. };
  58394. /**
  58395. * Add a new key and its corresponding value
  58396. * @param key the key to add
  58397. * @param value the value corresponding to the key
  58398. * @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
  58399. */
  58400. StringDictionary.prototype.add = function (key, value) {
  58401. if (this._data[key] !== undefined) {
  58402. return false;
  58403. }
  58404. this._data[key] = value;
  58405. ++this._count;
  58406. return true;
  58407. };
  58408. StringDictionary.prototype.set = function (key, value) {
  58409. if (this._data[key] === undefined) {
  58410. return false;
  58411. }
  58412. this._data[key] = value;
  58413. return true;
  58414. };
  58415. /**
  58416. * Get the element of the given key and remove it from the dictionary
  58417. * @param key
  58418. */
  58419. StringDictionary.prototype.getAndRemove = function (key) {
  58420. var val = this.get(key);
  58421. if (val !== undefined) {
  58422. delete this._data[key];
  58423. --this._count;
  58424. return val;
  58425. }
  58426. return null;
  58427. };
  58428. /**
  58429. * Remove a key/value from the dictionary.
  58430. * @param key the key to remove
  58431. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  58432. */
  58433. StringDictionary.prototype.remove = function (key) {
  58434. if (this.contains(key)) {
  58435. delete this._data[key];
  58436. --this._count;
  58437. return true;
  58438. }
  58439. return false;
  58440. };
  58441. /**
  58442. * Clear the whole content of the dictionary
  58443. */
  58444. StringDictionary.prototype.clear = function () {
  58445. this._data = {};
  58446. this._count = 0;
  58447. };
  58448. Object.defineProperty(StringDictionary.prototype, "count", {
  58449. get: function () {
  58450. return this._count;
  58451. },
  58452. enumerable: true,
  58453. configurable: true
  58454. });
  58455. /**
  58456. * Execute a callback on each key/val of the dictionary.
  58457. * Note that you can remove any element in this dictionary in the callback implementation
  58458. * @param callback the callback to execute on a given key/value pair
  58459. */
  58460. StringDictionary.prototype.forEach = function (callback) {
  58461. for (var cur in this._data) {
  58462. var val = this._data[cur];
  58463. callback(cur, val);
  58464. }
  58465. };
  58466. /**
  58467. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  58468. * If the callback returns null or undefined the method will iterate to the next key/value pair
  58469. * Note that you can remove any element in this dictionary in the callback implementation
  58470. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  58471. */
  58472. StringDictionary.prototype.first = function (callback) {
  58473. for (var cur in this._data) {
  58474. var val = this._data[cur];
  58475. var res = callback(cur, val);
  58476. if (res) {
  58477. return res;
  58478. }
  58479. }
  58480. return null;
  58481. };
  58482. return StringDictionary;
  58483. }());
  58484. BABYLON.StringDictionary = StringDictionary;
  58485. })(BABYLON || (BABYLON = {}));
  58486. //# sourceMappingURL=babylon.stringDictionary.js.map
  58487. var BABYLON;
  58488. (function (BABYLON) {
  58489. var Debug;
  58490. (function (Debug) {
  58491. /**
  58492. * Class used to render a debug view of a given skeleton
  58493. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  58494. */
  58495. var SkeletonViewer = /** @class */ (function () {
  58496. /**
  58497. * Creates a new SkeletonViewer
  58498. * @param skeleton defines the skeleton to render
  58499. * @param mesh defines the mesh attached to the skeleton
  58500. * @param scene defines the hosting scene
  58501. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  58502. * @param renderingGroupId defines the rendering group id to use with the viewer
  58503. */
  58504. function SkeletonViewer(
  58505. /** defines the skeleton to render */
  58506. skeleton,
  58507. /** defines the mesh attached to the skeleton */
  58508. mesh, scene,
  58509. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  58510. autoUpdateBonesMatrices,
  58511. /** defines the rendering group id to use with the viewer */
  58512. renderingGroupId) {
  58513. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  58514. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  58515. this.skeleton = skeleton;
  58516. this.mesh = mesh;
  58517. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  58518. this.renderingGroupId = renderingGroupId;
  58519. /** Gets or sets the color used to render the skeleton */
  58520. this.color = BABYLON.Color3.White();
  58521. this._debugLines = new Array();
  58522. this._isEnabled = false;
  58523. this._scene = scene;
  58524. this.update();
  58525. this._renderFunction = this.update.bind(this);
  58526. }
  58527. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  58528. get: function () {
  58529. return this._isEnabled;
  58530. },
  58531. /** Gets or sets a boolean indicating if the viewer is enabled */
  58532. set: function (value) {
  58533. if (this._isEnabled === value) {
  58534. return;
  58535. }
  58536. this._isEnabled = value;
  58537. if (value) {
  58538. this._scene.registerBeforeRender(this._renderFunction);
  58539. }
  58540. else {
  58541. this._scene.unregisterBeforeRender(this._renderFunction);
  58542. }
  58543. },
  58544. enumerable: true,
  58545. configurable: true
  58546. });
  58547. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  58548. if (x === void 0) { x = 0; }
  58549. if (y === void 0) { y = 0; }
  58550. if (z === void 0) { z = 0; }
  58551. var tmat = BABYLON.Tmp.Matrix[0];
  58552. var parentBone = bone.getParent();
  58553. tmat.copyFrom(bone.getLocalMatrix());
  58554. if (x !== 0 || y !== 0 || z !== 0) {
  58555. var tmat2 = BABYLON.Tmp.Matrix[1];
  58556. BABYLON.Matrix.IdentityToRef(tmat2);
  58557. tmat2.m[12] = x;
  58558. tmat2.m[13] = y;
  58559. tmat2.m[14] = z;
  58560. tmat2.multiplyToRef(tmat, tmat);
  58561. }
  58562. if (parentBone) {
  58563. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  58564. }
  58565. tmat.multiplyToRef(meshMat, tmat);
  58566. position.x = tmat.m[12];
  58567. position.y = tmat.m[13];
  58568. position.z = tmat.m[14];
  58569. };
  58570. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  58571. var len = bones.length;
  58572. var meshPos = this.mesh.position;
  58573. for (var i = 0; i < len; i++) {
  58574. var bone = bones[i];
  58575. var points = this._debugLines[i];
  58576. if (!points) {
  58577. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58578. this._debugLines[i] = points;
  58579. }
  58580. this._getBonePosition(points[0], bone, meshMat);
  58581. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  58582. points[0].subtractInPlace(meshPos);
  58583. points[1].subtractInPlace(meshPos);
  58584. }
  58585. };
  58586. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  58587. var len = bones.length;
  58588. var boneNum = 0;
  58589. var meshPos = this.mesh.position;
  58590. for (var i = len - 1; i >= 0; i--) {
  58591. var childBone = bones[i];
  58592. var parentBone = childBone.getParent();
  58593. if (!parentBone) {
  58594. continue;
  58595. }
  58596. var points = this._debugLines[boneNum];
  58597. if (!points) {
  58598. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58599. this._debugLines[boneNum] = points;
  58600. }
  58601. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  58602. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  58603. points[0].subtractInPlace(meshPos);
  58604. points[1].subtractInPlace(meshPos);
  58605. boneNum++;
  58606. }
  58607. };
  58608. /** Update the viewer to sync with current skeleton state */
  58609. SkeletonViewer.prototype.update = function () {
  58610. if (this.autoUpdateBonesMatrices) {
  58611. this.skeleton.computeAbsoluteTransforms();
  58612. }
  58613. if (this.skeleton.bones[0].length === undefined) {
  58614. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58615. }
  58616. else {
  58617. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  58618. }
  58619. if (!this._debugMesh) {
  58620. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  58621. this._debugMesh.renderingGroupId = this.renderingGroupId;
  58622. }
  58623. else {
  58624. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  58625. }
  58626. this._debugMesh.position.copyFrom(this.mesh.position);
  58627. this._debugMesh.color = this.color;
  58628. };
  58629. /** Release associated resources */
  58630. SkeletonViewer.prototype.dispose = function () {
  58631. if (this._debugMesh) {
  58632. this.isEnabled = false;
  58633. this._debugMesh.dispose();
  58634. this._debugMesh = null;
  58635. }
  58636. };
  58637. return SkeletonViewer;
  58638. }());
  58639. Debug.SkeletonViewer = SkeletonViewer;
  58640. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58641. })(BABYLON || (BABYLON = {}));
  58642. //# sourceMappingURL=babylon.skeletonViewer.js.map
  58643. /**
  58644. * Module Debug contains the (visual) components to debug a scene correctly
  58645. */
  58646. var BABYLON;
  58647. (function (BABYLON) {
  58648. var Debug;
  58649. (function (Debug) {
  58650. /**
  58651. * The Axes viewer will show 3 axes in a specific point in space
  58652. */
  58653. var AxesViewer = /** @class */ (function () {
  58654. /**
  58655. * Creates a new AxesViewer
  58656. * @param scene defines the hosting scene
  58657. * @param scaleLines defines a number used to scale line length (1 by default)
  58658. */
  58659. function AxesViewer(scene, scaleLines) {
  58660. if (scaleLines === void 0) { scaleLines = 1; }
  58661. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58662. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58663. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  58664. /**
  58665. * Gets or sets a number used to scale line length
  58666. */
  58667. this.scaleLines = 1;
  58668. this.scaleLines = scaleLines;
  58669. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  58670. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  58671. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  58672. this._xmesh.renderingGroupId = 2;
  58673. this._ymesh.renderingGroupId = 2;
  58674. this._zmesh.renderingGroupId = 2;
  58675. this._xmesh.material.checkReadyOnlyOnce = true;
  58676. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  58677. this._ymesh.material.checkReadyOnlyOnce = true;
  58678. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  58679. this._zmesh.material.checkReadyOnlyOnce = true;
  58680. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  58681. this.scene = scene;
  58682. }
  58683. /**
  58684. * Force the viewer to update
  58685. * @param position defines the position of the viewer
  58686. * @param xaxis defines the x axis of the viewer
  58687. * @param yaxis defines the y axis of the viewer
  58688. * @param zaxis defines the z axis of the viewer
  58689. */
  58690. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  58691. var scaleLines = this.scaleLines;
  58692. if (this._xmesh) {
  58693. this._xmesh.position.copyFrom(position);
  58694. }
  58695. if (this._ymesh) {
  58696. this._ymesh.position.copyFrom(position);
  58697. }
  58698. if (this._zmesh) {
  58699. this._zmesh.position.copyFrom(position);
  58700. }
  58701. var point2 = this._xline[1];
  58702. point2.x = xaxis.x * scaleLines;
  58703. point2.y = xaxis.y * scaleLines;
  58704. point2.z = xaxis.z * scaleLines;
  58705. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  58706. point2 = this._yline[1];
  58707. point2.x = yaxis.x * scaleLines;
  58708. point2.y = yaxis.y * scaleLines;
  58709. point2.z = yaxis.z * scaleLines;
  58710. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  58711. point2 = this._zline[1];
  58712. point2.x = zaxis.x * scaleLines;
  58713. point2.y = zaxis.y * scaleLines;
  58714. point2.z = zaxis.z * scaleLines;
  58715. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  58716. };
  58717. /** Releases resources */
  58718. AxesViewer.prototype.dispose = function () {
  58719. if (this._xmesh) {
  58720. this._xmesh.dispose();
  58721. }
  58722. if (this._ymesh) {
  58723. this._ymesh.dispose();
  58724. }
  58725. if (this._zmesh) {
  58726. this._zmesh.dispose();
  58727. }
  58728. this._xmesh = null;
  58729. this._ymesh = null;
  58730. this._zmesh = null;
  58731. this.scene = null;
  58732. };
  58733. return AxesViewer;
  58734. }());
  58735. Debug.AxesViewer = AxesViewer;
  58736. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58737. })(BABYLON || (BABYLON = {}));
  58738. //# sourceMappingURL=babylon.axesViewer.js.map
  58739. var BABYLON;
  58740. (function (BABYLON) {
  58741. var Debug;
  58742. (function (Debug) {
  58743. /**
  58744. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  58745. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  58746. */
  58747. var BoneAxesViewer = /** @class */ (function (_super) {
  58748. __extends(BoneAxesViewer, _super);
  58749. /**
  58750. * Creates a new BoneAxesViewer
  58751. * @param scene defines the hosting scene
  58752. * @param bone defines the target bone
  58753. * @param mesh defines the target mesh
  58754. * @param scaleLines defines a scaling factor for line length (1 by default)
  58755. */
  58756. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  58757. if (scaleLines === void 0) { scaleLines = 1; }
  58758. var _this = _super.call(this, scene, scaleLines) || this;
  58759. /** Gets current position */
  58760. _this.pos = BABYLON.Vector3.Zero();
  58761. /** Gets direction of X axis */
  58762. _this.xaxis = BABYLON.Vector3.Zero();
  58763. /** Gets direction of Y axis */
  58764. _this.yaxis = BABYLON.Vector3.Zero();
  58765. /** Gets direction of Z axis */
  58766. _this.zaxis = BABYLON.Vector3.Zero();
  58767. _this.mesh = mesh;
  58768. _this.bone = bone;
  58769. return _this;
  58770. }
  58771. /**
  58772. * Force the viewer to update
  58773. */
  58774. BoneAxesViewer.prototype.update = function () {
  58775. if (!this.mesh || !this.bone) {
  58776. return;
  58777. }
  58778. var bone = this.bone;
  58779. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  58780. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  58781. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  58782. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  58783. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  58784. };
  58785. /** Releases resources */
  58786. BoneAxesViewer.prototype.dispose = function () {
  58787. if (this.mesh) {
  58788. this.mesh = null;
  58789. this.bone = null;
  58790. _super.prototype.dispose.call(this);
  58791. }
  58792. };
  58793. return BoneAxesViewer;
  58794. }(Debug.AxesViewer));
  58795. Debug.BoneAxesViewer = BoneAxesViewer;
  58796. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  58797. })(BABYLON || (BABYLON = {}));
  58798. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  58799. var BABYLON;
  58800. (function (BABYLON) {
  58801. var RayHelper = /** @class */ (function () {
  58802. function RayHelper(ray) {
  58803. this.ray = ray;
  58804. }
  58805. RayHelper.CreateAndShow = function (ray, scene, color) {
  58806. var helper = new RayHelper(ray);
  58807. helper.show(scene, color);
  58808. return helper;
  58809. };
  58810. RayHelper.prototype.show = function (scene, color) {
  58811. if (!this._renderFunction && this.ray) {
  58812. var ray = this.ray;
  58813. this._renderFunction = this._render.bind(this);
  58814. this._scene = scene;
  58815. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  58816. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  58817. if (this._renderFunction) {
  58818. this._scene.registerBeforeRender(this._renderFunction);
  58819. }
  58820. }
  58821. if (color && this._renderLine) {
  58822. this._renderLine.color.copyFrom(color);
  58823. }
  58824. };
  58825. RayHelper.prototype.hide = function () {
  58826. if (this._renderFunction && this._scene) {
  58827. this._scene.unregisterBeforeRender(this._renderFunction);
  58828. this._scene = null;
  58829. this._renderFunction = null;
  58830. if (this._renderLine) {
  58831. this._renderLine.dispose();
  58832. this._renderLine = null;
  58833. }
  58834. this._renderPoints = [];
  58835. }
  58836. };
  58837. RayHelper.prototype._render = function () {
  58838. var ray = this.ray;
  58839. if (!ray) {
  58840. return;
  58841. }
  58842. var point = this._renderPoints[1];
  58843. var len = Math.min(ray.length, 1000000);
  58844. point.copyFrom(ray.direction);
  58845. point.scaleInPlace(len);
  58846. point.addInPlace(ray.origin);
  58847. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  58848. };
  58849. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  58850. this._attachedToMesh = mesh;
  58851. var ray = this.ray;
  58852. if (!ray) {
  58853. return;
  58854. }
  58855. if (!ray.direction) {
  58856. ray.direction = BABYLON.Vector3.Zero();
  58857. }
  58858. if (!ray.origin) {
  58859. ray.origin = BABYLON.Vector3.Zero();
  58860. }
  58861. if (length) {
  58862. ray.length = length;
  58863. }
  58864. if (!meshSpaceOrigin) {
  58865. meshSpaceOrigin = BABYLON.Vector3.Zero();
  58866. }
  58867. if (!meshSpaceDirection) {
  58868. // -1 so that this will work with Mesh.lookAt
  58869. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  58870. }
  58871. if (!this._meshSpaceDirection) {
  58872. this._meshSpaceDirection = meshSpaceDirection.clone();
  58873. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  58874. }
  58875. else {
  58876. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  58877. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  58878. }
  58879. if (!this._updateToMeshFunction) {
  58880. this._updateToMeshFunction = this._updateToMesh.bind(this);
  58881. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  58882. }
  58883. this._updateToMesh();
  58884. };
  58885. RayHelper.prototype.detachFromMesh = function () {
  58886. if (this._attachedToMesh) {
  58887. if (this._updateToMeshFunction) {
  58888. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  58889. }
  58890. this._attachedToMesh = null;
  58891. this._updateToMeshFunction = null;
  58892. }
  58893. };
  58894. RayHelper.prototype._updateToMesh = function () {
  58895. var ray = this.ray;
  58896. if (!this._attachedToMesh || !ray) {
  58897. return;
  58898. }
  58899. if (this._attachedToMesh._isDisposed) {
  58900. this.detachFromMesh();
  58901. return;
  58902. }
  58903. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  58904. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  58905. };
  58906. RayHelper.prototype.dispose = function () {
  58907. this.hide();
  58908. this.detachFromMesh();
  58909. this.ray = null;
  58910. };
  58911. return RayHelper;
  58912. }());
  58913. BABYLON.RayHelper = RayHelper;
  58914. })(BABYLON || (BABYLON = {}));
  58915. //# sourceMappingURL=babylon.rayHelper.js.map
  58916. var BABYLON;
  58917. (function (BABYLON) {
  58918. // load the inspector using require, if not present in the global namespace.
  58919. var DebugLayer = /** @class */ (function () {
  58920. function DebugLayer(scene) {
  58921. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58922. this.onPropertyChangedObservable = new BABYLON.Observable();
  58923. this._scene = scene;
  58924. }
  58925. /** Creates the inspector window. */
  58926. DebugLayer.prototype._createInspector = function (config) {
  58927. if (config === void 0) { config = {}; }
  58928. var popup = config.popup || false;
  58929. var initialTab = config.initialTab || 0;
  58930. var parentElement = config.parentElement || null;
  58931. if (!this._inspector) {
  58932. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  58933. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  58934. } // else nothing to do as instance is already created
  58935. };
  58936. DebugLayer.prototype.isVisible = function () {
  58937. if (!this._inspector) {
  58938. return false;
  58939. }
  58940. return true;
  58941. };
  58942. DebugLayer.prototype.hide = function () {
  58943. if (this._inspector) {
  58944. try {
  58945. this._inspector.dispose();
  58946. }
  58947. catch (e) {
  58948. // If the inspector has been removed directly from the inspector tool
  58949. }
  58950. this.onPropertyChangedObservable.clear();
  58951. this._inspector = null;
  58952. }
  58953. };
  58954. /**
  58955. *
  58956. * Launch the debugLayer.
  58957. *
  58958. * initialTab:
  58959. * | Value | Tab Name |
  58960. * | --- | --- |
  58961. * | 0 | Scene |
  58962. * | 1 | Console |
  58963. * | 2 | Stats |
  58964. * | 3 | Textures |
  58965. * | 4 | Mesh |
  58966. * | 5 | Light |
  58967. * | 6 | Material |
  58968. * | 7 | GLTF |
  58969. * | 8 | GUI |
  58970. * | 9 | Physics |
  58971. * | 10 | Camera |
  58972. * | 11 | Audio |
  58973. *
  58974. */
  58975. DebugLayer.prototype.show = function (config) {
  58976. if (config === void 0) { config = {}; }
  58977. if (typeof this.BJSINSPECTOR == 'undefined') {
  58978. // Load inspector and add it to the DOM
  58979. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  58980. }
  58981. else {
  58982. // Otherwise creates the inspector
  58983. this._createInspector(config);
  58984. }
  58985. };
  58986. /**
  58987. * Gets the active tab
  58988. * @return the index of the active tab or -1 if the inspector is hidden
  58989. */
  58990. DebugLayer.prototype.getActiveTab = function () {
  58991. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  58992. };
  58993. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  58994. return DebugLayer;
  58995. }());
  58996. BABYLON.DebugLayer = DebugLayer;
  58997. })(BABYLON || (BABYLON = {}));
  58998. //# sourceMappingURL=babylon.debugLayer.js.map
  58999. var BABYLON;
  59000. (function (BABYLON) {
  59001. var Debug;
  59002. (function (Debug) {
  59003. /**
  59004. * Used to show the physics impostor around the specific mesh
  59005. */
  59006. var PhysicsViewer = /** @class */ (function () {
  59007. /**
  59008. * Creates a new PhysicsViewer
  59009. * @param scene defines the hosting scene
  59010. */
  59011. function PhysicsViewer(scene) {
  59012. /** @hidden */
  59013. this._impostors = [];
  59014. /** @hidden */
  59015. this._meshes = [];
  59016. /** @hidden */
  59017. this._numMeshes = 0;
  59018. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59019. var physicEngine = this._scene.getPhysicsEngine();
  59020. if (physicEngine) {
  59021. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  59022. }
  59023. }
  59024. /** @hidden */
  59025. PhysicsViewer.prototype._updateDebugMeshes = function () {
  59026. var plugin = this._physicsEnginePlugin;
  59027. for (var i = 0; i < this._numMeshes; i++) {
  59028. var impostor = this._impostors[i];
  59029. if (!impostor) {
  59030. continue;
  59031. }
  59032. if (impostor.isDisposed) {
  59033. this.hideImpostor(this._impostors[i--]);
  59034. }
  59035. else {
  59036. var mesh = this._meshes[i];
  59037. if (mesh && plugin) {
  59038. plugin.syncMeshWithImpostor(mesh, impostor);
  59039. }
  59040. }
  59041. }
  59042. };
  59043. /**
  59044. * Renders a specified physic impostor
  59045. * @param impostor defines the impostor to render
  59046. */
  59047. PhysicsViewer.prototype.showImpostor = function (impostor) {
  59048. if (!this._scene) {
  59049. return;
  59050. }
  59051. for (var i = 0; i < this._numMeshes; i++) {
  59052. if (this._impostors[i] == impostor) {
  59053. return;
  59054. }
  59055. }
  59056. var debugMesh = this._getDebugMesh(impostor, this._scene);
  59057. if (debugMesh) {
  59058. this._impostors[this._numMeshes] = impostor;
  59059. this._meshes[this._numMeshes] = debugMesh;
  59060. if (this._numMeshes === 0) {
  59061. this._renderFunction = this._updateDebugMeshes.bind(this);
  59062. this._scene.registerBeforeRender(this._renderFunction);
  59063. }
  59064. this._numMeshes++;
  59065. }
  59066. };
  59067. /**
  59068. * Hides a specified physic impostor
  59069. * @param impostor defines the impostor to hide
  59070. */
  59071. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  59072. if (!impostor || !this._scene) {
  59073. return;
  59074. }
  59075. var removed = false;
  59076. for (var i = 0; i < this._numMeshes; i++) {
  59077. if (this._impostors[i] == impostor) {
  59078. var mesh = this._meshes[i];
  59079. if (!mesh) {
  59080. continue;
  59081. }
  59082. this._scene.removeMesh(mesh);
  59083. mesh.dispose();
  59084. this._numMeshes--;
  59085. if (this._numMeshes > 0) {
  59086. this._meshes[i] = this._meshes[this._numMeshes];
  59087. this._impostors[i] = this._impostors[this._numMeshes];
  59088. this._meshes[this._numMeshes] = null;
  59089. this._impostors[this._numMeshes] = null;
  59090. }
  59091. else {
  59092. this._meshes[0] = null;
  59093. this._impostors[0] = null;
  59094. }
  59095. removed = true;
  59096. break;
  59097. }
  59098. }
  59099. if (removed && this._numMeshes === 0) {
  59100. this._scene.unregisterBeforeRender(this._renderFunction);
  59101. }
  59102. };
  59103. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  59104. if (!this._debugMaterial) {
  59105. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  59106. this._debugMaterial.wireframe = true;
  59107. }
  59108. return this._debugMaterial;
  59109. };
  59110. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  59111. if (!this._debugBoxMesh) {
  59112. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  59113. this._debugBoxMesh.renderingGroupId = 1;
  59114. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59115. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  59116. scene.removeMesh(this._debugBoxMesh);
  59117. }
  59118. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  59119. };
  59120. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  59121. if (!this._debugSphereMesh) {
  59122. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  59123. this._debugSphereMesh.renderingGroupId = 1;
  59124. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  59125. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  59126. scene.removeMesh(this._debugSphereMesh);
  59127. }
  59128. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  59129. };
  59130. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  59131. var mesh = null;
  59132. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  59133. mesh = this._getDebugBoxMesh(scene);
  59134. impostor.getBoxSizeToRef(mesh.scaling);
  59135. }
  59136. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  59137. mesh = this._getDebugSphereMesh(scene);
  59138. var radius = impostor.getRadius();
  59139. mesh.scaling.x = radius * 2;
  59140. mesh.scaling.y = radius * 2;
  59141. mesh.scaling.z = radius * 2;
  59142. }
  59143. return mesh;
  59144. };
  59145. /** Releases all resources */
  59146. PhysicsViewer.prototype.dispose = function () {
  59147. for (var i = 0; i < this._numMeshes; i++) {
  59148. this.hideImpostor(this._impostors[i]);
  59149. }
  59150. if (this._debugBoxMesh) {
  59151. this._debugBoxMesh.dispose();
  59152. }
  59153. if (this._debugSphereMesh) {
  59154. this._debugSphereMesh.dispose();
  59155. }
  59156. if (this._debugMaterial) {
  59157. this._debugMaterial.dispose();
  59158. }
  59159. this._impostors.length = 0;
  59160. this._scene = null;
  59161. this._physicsEnginePlugin = null;
  59162. };
  59163. return PhysicsViewer;
  59164. }());
  59165. Debug.PhysicsViewer = PhysicsViewer;
  59166. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59167. })(BABYLON || (BABYLON = {}));
  59168. //# sourceMappingURL=babylon.physicsViewer.js.map
  59169. var BABYLON;
  59170. (function (BABYLON) {
  59171. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  59172. get: function () {
  59173. return this._forceShowBoundingBoxes || false;
  59174. },
  59175. set: function (value) {
  59176. this._forceShowBoundingBoxes = value;
  59177. // Lazyly creates a BB renderer if needed.
  59178. if (value) {
  59179. this.getBoundingBoxRenderer();
  59180. }
  59181. },
  59182. enumerable: true,
  59183. configurable: true
  59184. });
  59185. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  59186. if (!this._boundingBoxRenderer) {
  59187. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  59188. }
  59189. return this._boundingBoxRenderer;
  59190. };
  59191. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  59192. get: function () {
  59193. return this._showBoundingBox || false;
  59194. },
  59195. set: function (value) {
  59196. this._showBoundingBox = value;
  59197. // Lazyly creates a BB renderer if needed.
  59198. if (value) {
  59199. this.getScene().getBoundingBoxRenderer();
  59200. }
  59201. },
  59202. enumerable: true,
  59203. configurable: true
  59204. });
  59205. var BoundingBoxRenderer = /** @class */ (function () {
  59206. function BoundingBoxRenderer(scene) {
  59207. /**
  59208. * The component name helpfull to identify the component in the list of scene components.
  59209. */
  59210. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  59211. this.frontColor = new BABYLON.Color3(1, 1, 1);
  59212. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  59213. this.showBackLines = true;
  59214. this.renderList = new BABYLON.SmartArray(32);
  59215. this._vertexBuffers = {};
  59216. this.scene = scene;
  59217. scene._addComponent(this);
  59218. }
  59219. /**
  59220. * Registers the component in a given scene
  59221. */
  59222. BoundingBoxRenderer.prototype.register = function () {
  59223. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  59224. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  59225. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  59226. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  59227. };
  59228. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  59229. if (mesh.showSubMeshesBoundingBox) {
  59230. var boundingInfo = subMesh.getBoundingInfo();
  59231. if (boundingInfo !== null && boundingInfo !== undefined) {
  59232. this.renderList.push(boundingInfo.boundingBox);
  59233. }
  59234. }
  59235. };
  59236. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  59237. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  59238. var boundingInfo = sourceMesh.getBoundingInfo();
  59239. this.renderList.push(boundingInfo.boundingBox);
  59240. }
  59241. };
  59242. BoundingBoxRenderer.prototype._prepareRessources = function () {
  59243. if (this._colorShader) {
  59244. return;
  59245. }
  59246. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  59247. attributes: [BABYLON.VertexBuffer.PositionKind],
  59248. uniforms: ["world", "viewProjection", "color"]
  59249. });
  59250. var engine = this.scene.getEngine();
  59251. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  59252. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  59253. this._createIndexBuffer();
  59254. };
  59255. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  59256. var engine = this.scene.getEngine();
  59257. 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]);
  59258. };
  59259. /**
  59260. * Rebuilds the elements related to this component in case of
  59261. * context lost for instance.
  59262. */
  59263. BoundingBoxRenderer.prototype.rebuild = function () {
  59264. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59265. if (vb) {
  59266. vb._rebuild();
  59267. }
  59268. this._createIndexBuffer();
  59269. };
  59270. BoundingBoxRenderer.prototype.reset = function () {
  59271. this.renderList.reset();
  59272. };
  59273. BoundingBoxRenderer.prototype.render = function () {
  59274. if (this.renderList.length === 0) {
  59275. return;
  59276. }
  59277. this._prepareRessources();
  59278. if (!this._colorShader.isReady()) {
  59279. return;
  59280. }
  59281. var engine = this.scene.getEngine();
  59282. engine.setDepthWrite(false);
  59283. this._colorShader._preBind();
  59284. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  59285. var boundingBox = this.renderList.data[boundingBoxIndex];
  59286. var min = boundingBox.minimum;
  59287. var max = boundingBox.maximum;
  59288. var diff = max.subtract(min);
  59289. var median = min.add(diff.scale(0.5));
  59290. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59291. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59292. .multiply(boundingBox.getWorldMatrix());
  59293. // VBOs
  59294. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59295. if (this.showBackLines) {
  59296. // Back
  59297. engine.setDepthFunctionToGreaterOrEqual();
  59298. this.scene.resetCachedMaterial();
  59299. this._colorShader.setColor4("color", this.backColor.toColor4());
  59300. this._colorShader.bind(worldMatrix);
  59301. // Draw order
  59302. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59303. }
  59304. // Front
  59305. engine.setDepthFunctionToLess();
  59306. this.scene.resetCachedMaterial();
  59307. this._colorShader.setColor4("color", this.frontColor.toColor4());
  59308. this._colorShader.bind(worldMatrix);
  59309. // Draw order
  59310. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59311. }
  59312. this._colorShader.unbind();
  59313. engine.setDepthFunctionToLessOrEqual();
  59314. engine.setDepthWrite(true);
  59315. };
  59316. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  59317. this._prepareRessources();
  59318. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  59319. return;
  59320. }
  59321. var engine = this.scene.getEngine();
  59322. engine.setDepthWrite(false);
  59323. engine.setColorWrite(false);
  59324. this._colorShader._preBind();
  59325. var boundingBox = mesh._boundingInfo.boundingBox;
  59326. var min = boundingBox.minimum;
  59327. var max = boundingBox.maximum;
  59328. var diff = max.subtract(min);
  59329. var median = min.add(diff.scale(0.5));
  59330. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  59331. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  59332. .multiply(boundingBox.getWorldMatrix());
  59333. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  59334. engine.setDepthFunctionToLess();
  59335. this.scene.resetCachedMaterial();
  59336. this._colorShader.bind(worldMatrix);
  59337. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  59338. this._colorShader.unbind();
  59339. engine.setDepthFunctionToLessOrEqual();
  59340. engine.setDepthWrite(true);
  59341. engine.setColorWrite(true);
  59342. };
  59343. BoundingBoxRenderer.prototype.dispose = function () {
  59344. if (!this._colorShader) {
  59345. return;
  59346. }
  59347. this.renderList.dispose();
  59348. this._colorShader.dispose();
  59349. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59350. if (buffer) {
  59351. buffer.dispose();
  59352. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59353. }
  59354. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  59355. };
  59356. return BoundingBoxRenderer;
  59357. }());
  59358. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  59359. })(BABYLON || (BABYLON = {}));
  59360. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  59361. var BABYLON;
  59362. (function (BABYLON) {
  59363. BABYLON.Engine.prototype.createTransformFeedback = function () {
  59364. return this._gl.createTransformFeedback();
  59365. };
  59366. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  59367. this._gl.deleteTransformFeedback(value);
  59368. };
  59369. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  59370. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  59371. };
  59372. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  59373. if (usePoints === void 0) { usePoints = true; }
  59374. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  59375. };
  59376. BABYLON.Engine.prototype.endTransformFeedback = function () {
  59377. this._gl.endTransformFeedback();
  59378. };
  59379. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  59380. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  59381. };
  59382. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  59383. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  59384. };
  59385. })(BABYLON || (BABYLON = {}));
  59386. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  59387. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59388. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59389. s = arguments[i];
  59390. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59391. t[p] = s[p];
  59392. }
  59393. return t;
  59394. };
  59395. var BABYLON;
  59396. (function (BABYLON) {
  59397. /**
  59398. * This represents a GPU particle system in Babylon
  59399. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  59400. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  59401. */
  59402. var GPUParticleSystem = /** @class */ (function () {
  59403. /**
  59404. * Instantiates a GPU particle system.
  59405. * 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.
  59406. * @param name The name of the particle system
  59407. * @param options The options used to create the system
  59408. * @param scene The scene the particle system belongs to
  59409. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  59410. */
  59411. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  59412. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  59413. /**
  59414. * The emitter represents the Mesh or position we are attaching the particle system to.
  59415. */
  59416. this.emitter = null;
  59417. /**
  59418. * The rendering group used by the Particle system to chose when to render.
  59419. */
  59420. this.renderingGroupId = 0;
  59421. /**
  59422. * The layer mask we are rendering the particles through.
  59423. */
  59424. this.layerMask = 0x0FFFFFFF;
  59425. this._accumulatedCount = 0;
  59426. this._targetIndex = 0;
  59427. this._currentRenderId = -1;
  59428. this._started = false;
  59429. this._stopped = false;
  59430. this._timeDelta = 0;
  59431. this._attributesStrideSize = 21;
  59432. this._actualFrame = 0;
  59433. this._rawTextureWidth = 256;
  59434. /**
  59435. * List of animations used by the particle system.
  59436. */
  59437. this.animations = [];
  59438. /**
  59439. * An event triggered when the system is disposed.
  59440. */
  59441. this.onDisposeObservable = new BABYLON.Observable();
  59442. /**
  59443. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  59444. */
  59445. this.updateSpeed = 0.01;
  59446. /**
  59447. * The amount of time the particle system is running (depends of the overall update speed).
  59448. */
  59449. this.targetStopDuration = 0;
  59450. /**
  59451. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  59452. */
  59453. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  59454. /**
  59455. * Minimum life time of emitting particles.
  59456. */
  59457. this.minLifeTime = 1;
  59458. /**
  59459. * Maximum life time of emitting particles.
  59460. */
  59461. this.maxLifeTime = 1;
  59462. /**
  59463. * Minimum Size of emitting particles.
  59464. */
  59465. this.minSize = 1;
  59466. /**
  59467. * Maximum Size of emitting particles.
  59468. */
  59469. this.maxSize = 1;
  59470. /**
  59471. * Minimum scale of emitting particles on X axis.
  59472. */
  59473. this.minScaleX = 1;
  59474. /**
  59475. * Maximum scale of emitting particles on X axis.
  59476. */
  59477. this.maxScaleX = 1;
  59478. /**
  59479. * Minimum scale of emitting particles on Y axis.
  59480. */
  59481. this.minScaleY = 1;
  59482. /**
  59483. * Maximum scale of emitting particles on Y axis.
  59484. */
  59485. this.maxScaleY = 1;
  59486. /**
  59487. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59488. */
  59489. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59490. /**
  59491. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  59492. */
  59493. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  59494. /**
  59495. * Color the particle will have at the end of its lifetime.
  59496. */
  59497. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  59498. /**
  59499. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  59500. */
  59501. this.emitRate = 100;
  59502. /**
  59503. * You can use gravity if you want to give an orientation to your particles.
  59504. */
  59505. this.gravity = BABYLON.Vector3.Zero();
  59506. /**
  59507. * Minimum power of emitting particles.
  59508. */
  59509. this.minEmitPower = 1;
  59510. /**
  59511. * Maximum power of emitting particles.
  59512. */
  59513. this.maxEmitPower = 1;
  59514. /**
  59515. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  59516. */
  59517. this.minAngularSpeed = 0;
  59518. /**
  59519. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  59520. */
  59521. this.maxAngularSpeed = 0;
  59522. /**
  59523. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  59524. * to override the particles.
  59525. */
  59526. this.forceDepthWrite = false;
  59527. this._preWarmDone = false;
  59528. /** 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 */
  59529. this.preWarmCycles = 0;
  59530. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  59531. this.preWarmStepOffset = 1;
  59532. /**
  59533. * Gets or sets the minimal initial rotation in radians.
  59534. */
  59535. this.minInitialRotation = 0;
  59536. /**
  59537. * Gets or sets the maximal initial rotation in radians.
  59538. */
  59539. this.maxInitialRotation = 0;
  59540. /**
  59541. * 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)
  59542. */
  59543. this.spriteCellChangeSpeed = 1;
  59544. /**
  59545. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  59546. */
  59547. this.startSpriteCellID = 0;
  59548. /**
  59549. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  59550. */
  59551. this.endSpriteCellID = 0;
  59552. /**
  59553. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  59554. */
  59555. this.spriteCellWidth = 0;
  59556. /**
  59557. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  59558. */
  59559. this.spriteCellHeight = 0;
  59560. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  59561. this.translationPivot = new BABYLON.Vector2(0, 0);
  59562. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  59563. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  59564. /**
  59565. * Gets or sets the billboard mode to use when isBillboardBased = true.
  59566. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  59567. */
  59568. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59569. this._isBillboardBased = true;
  59570. this._colorGradients = null;
  59571. this._angularSpeedGradients = null;
  59572. this._sizeGradients = null;
  59573. this._velocityGradients = null;
  59574. this.id = name;
  59575. this.name = name;
  59576. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59577. this._engine = this._scene.getEngine();
  59578. if (!options.randomTextureSize) {
  59579. delete options.randomTextureSize;
  59580. }
  59581. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  59582. var optionsAsNumber = options;
  59583. if (isFinite(optionsAsNumber)) {
  59584. fullOptions.capacity = optionsAsNumber;
  59585. }
  59586. this._capacity = fullOptions.capacity;
  59587. this._activeCount = fullOptions.capacity;
  59588. this._currentActiveCount = 0;
  59589. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59590. this._scene.particleSystems.push(this);
  59591. this._updateEffectOptions = {
  59592. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  59593. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  59594. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  59595. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  59596. uniformBuffersNames: [],
  59597. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  59598. defines: "",
  59599. fallbacks: null,
  59600. onCompiled: null,
  59601. onError: null,
  59602. indexParameters: null,
  59603. maxSimultaneousLights: 0,
  59604. transformFeedbackVaryings: []
  59605. };
  59606. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59607. // Random data
  59608. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  59609. var d = [];
  59610. for (var i = 0; i < maxTextureSize; ++i) {
  59611. d.push(Math.random());
  59612. d.push(Math.random());
  59613. d.push(Math.random());
  59614. d.push(Math.random());
  59615. }
  59616. 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);
  59617. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59618. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59619. d = [];
  59620. for (var i = 0; i < maxTextureSize; ++i) {
  59621. d.push(Math.random());
  59622. d.push(Math.random());
  59623. d.push(Math.random());
  59624. d.push(Math.random());
  59625. }
  59626. 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);
  59627. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59628. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59629. this._randomTextureSize = maxTextureSize;
  59630. }
  59631. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  59632. /**
  59633. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  59634. */
  59635. get: function () {
  59636. if (!BABYLON.Engine.LastCreatedEngine) {
  59637. return false;
  59638. }
  59639. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  59640. },
  59641. enumerable: true,
  59642. configurable: true
  59643. });
  59644. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  59645. /**
  59646. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59647. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59648. */
  59649. get: function () {
  59650. if (this.particleEmitterType.direction1) {
  59651. return this.particleEmitterType.direction1;
  59652. }
  59653. return BABYLON.Vector3.Zero();
  59654. },
  59655. set: function (value) {
  59656. if (this.particleEmitterType.direction1) {
  59657. this.particleEmitterType.direction1 = value;
  59658. }
  59659. },
  59660. enumerable: true,
  59661. configurable: true
  59662. });
  59663. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  59664. /**
  59665. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59666. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59667. */
  59668. get: function () {
  59669. if (this.particleEmitterType.direction2) {
  59670. return this.particleEmitterType.direction2;
  59671. }
  59672. return BABYLON.Vector3.Zero();
  59673. },
  59674. set: function (value) {
  59675. if (this.particleEmitterType.direction2) {
  59676. this.particleEmitterType.direction2 = value;
  59677. }
  59678. },
  59679. enumerable: true,
  59680. configurable: true
  59681. });
  59682. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  59683. /**
  59684. * 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.
  59685. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59686. */
  59687. get: function () {
  59688. if (this.particleEmitterType.minEmitBox) {
  59689. return this.particleEmitterType.minEmitBox;
  59690. }
  59691. return BABYLON.Vector3.Zero();
  59692. },
  59693. set: function (value) {
  59694. if (this.particleEmitterType.minEmitBox) {
  59695. this.particleEmitterType.minEmitBox = value;
  59696. }
  59697. },
  59698. enumerable: true,
  59699. configurable: true
  59700. });
  59701. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  59702. /**
  59703. * 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.
  59704. * This only works when particleEmitterTyps is a BoxParticleEmitter
  59705. */
  59706. get: function () {
  59707. if (this.particleEmitterType.maxEmitBox) {
  59708. return this.particleEmitterType.maxEmitBox;
  59709. }
  59710. return BABYLON.Vector3.Zero();
  59711. },
  59712. set: function (value) {
  59713. if (this.particleEmitterType.maxEmitBox) {
  59714. this.particleEmitterType.maxEmitBox = value;
  59715. }
  59716. },
  59717. enumerable: true,
  59718. configurable: true
  59719. });
  59720. /**
  59721. * Gets the maximum number of particles active at the same time.
  59722. * @returns The max number of active particles.
  59723. */
  59724. GPUParticleSystem.prototype.getCapacity = function () {
  59725. return this._capacity;
  59726. };
  59727. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  59728. /**
  59729. * Gets or set the number of active particles
  59730. */
  59731. get: function () {
  59732. return this._activeCount;
  59733. },
  59734. set: function (value) {
  59735. this._activeCount = Math.min(value, this._capacity);
  59736. },
  59737. enumerable: true,
  59738. configurable: true
  59739. });
  59740. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  59741. /**
  59742. * Gets whether an animation sprite sheet is enabled or not on the particle system
  59743. */
  59744. get: function () {
  59745. return this._isAnimationSheetEnabled;
  59746. },
  59747. enumerable: true,
  59748. configurable: true
  59749. });
  59750. /**
  59751. * Is this system ready to be used/rendered
  59752. * @return true if the system is ready
  59753. */
  59754. GPUParticleSystem.prototype.isReady = function () {
  59755. if (!this._updateEffect) {
  59756. this._recreateUpdateEffect();
  59757. this._recreateRenderEffect();
  59758. return false;
  59759. }
  59760. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  59761. return false;
  59762. }
  59763. return true;
  59764. };
  59765. /**
  59766. * Gets Wether the system has been started.
  59767. * @returns True if it has been started, otherwise false.
  59768. */
  59769. GPUParticleSystem.prototype.isStarted = function () {
  59770. return this._started;
  59771. };
  59772. /**
  59773. * Starts the particle system and begins to emit
  59774. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  59775. */
  59776. GPUParticleSystem.prototype.start = function (delay) {
  59777. var _this = this;
  59778. if (delay === void 0) { delay = 0; }
  59779. if (delay) {
  59780. setTimeout(function () {
  59781. _this.start(0);
  59782. }, delay);
  59783. return;
  59784. }
  59785. this._started = true;
  59786. this._stopped = false;
  59787. this._preWarmDone = false;
  59788. };
  59789. /**
  59790. * Stops the particle system.
  59791. */
  59792. GPUParticleSystem.prototype.stop = function () {
  59793. this._stopped = true;
  59794. };
  59795. /**
  59796. * Remove all active particles
  59797. */
  59798. GPUParticleSystem.prototype.reset = function () {
  59799. this._releaseBuffers();
  59800. this._releaseVAOs();
  59801. this._currentActiveCount = 0;
  59802. this._targetIndex = 0;
  59803. };
  59804. /**
  59805. * Returns the string "GPUParticleSystem"
  59806. * @returns a string containing the class name
  59807. */
  59808. GPUParticleSystem.prototype.getClassName = function () {
  59809. return "GPUParticleSystem";
  59810. };
  59811. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  59812. /**
  59813. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  59814. */
  59815. get: function () {
  59816. return this._isBillboardBased;
  59817. },
  59818. set: function (value) {
  59819. if (this._isBillboardBased === value) {
  59820. return;
  59821. }
  59822. this._isBillboardBased = value;
  59823. this._releaseBuffers();
  59824. },
  59825. enumerable: true,
  59826. configurable: true
  59827. });
  59828. /**
  59829. * Gets the current list of color gradients.
  59830. * You must use addColorGradient and removeColorGradient to udpate this list
  59831. * @returns the list of color gradients
  59832. */
  59833. GPUParticleSystem.prototype.getColorGradients = function () {
  59834. return this._colorGradients;
  59835. };
  59836. /**
  59837. * Gets the current list of size gradients.
  59838. * You must use addSizeGradient and removeSizeGradient to udpate this list
  59839. * @returns the list of size gradients
  59840. */
  59841. GPUParticleSystem.prototype.getSizeGradients = function () {
  59842. return this._sizeGradients;
  59843. };
  59844. /**
  59845. * Gets the current list of angular speed gradients.
  59846. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  59847. * @returns the list of angular speed gradients
  59848. */
  59849. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  59850. return this._angularSpeedGradients;
  59851. };
  59852. /**
  59853. * Gets the current list of velocity gradients.
  59854. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  59855. * @returns the list of angular speed gradients
  59856. */
  59857. GPUParticleSystem.prototype.getVelocityGradients = function () {
  59858. return this._velocityGradients;
  59859. };
  59860. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  59861. if (!gradients) {
  59862. return this;
  59863. }
  59864. var index = 0;
  59865. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  59866. var valueGradient = gradients_1[_i];
  59867. if (valueGradient.gradient === gradient) {
  59868. gradients.splice(index, 1);
  59869. break;
  59870. }
  59871. index++;
  59872. }
  59873. if (texture) {
  59874. texture.dispose();
  59875. }
  59876. this._releaseBuffers();
  59877. return this;
  59878. };
  59879. /**
  59880. * Adds a new color gradient
  59881. * @param gradient defines the gradient to use (between 0 and 1)
  59882. * @param color defines the color to affect to the specified gradient
  59883. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59884. * @returns the current particle system
  59885. */
  59886. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59887. if (!this._colorGradients) {
  59888. this._colorGradients = [];
  59889. }
  59890. var colorGradient = new BABYLON.ColorGradient();
  59891. colorGradient.gradient = gradient;
  59892. colorGradient.color1 = color1;
  59893. this._colorGradients.push(colorGradient);
  59894. this._colorGradients.sort(function (a, b) {
  59895. if (a.gradient < b.gradient) {
  59896. return -1;
  59897. }
  59898. else if (a.gradient > b.gradient) {
  59899. return 1;
  59900. }
  59901. return 0;
  59902. });
  59903. if (this._colorGradientsTexture) {
  59904. this._colorGradientsTexture.dispose();
  59905. this._colorGradientsTexture = null;
  59906. }
  59907. this._releaseBuffers();
  59908. return this;
  59909. };
  59910. /**
  59911. * Remove a specific color gradient
  59912. * @param gradient defines the gradient to remove
  59913. * @returns the current particle system
  59914. */
  59915. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  59916. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  59917. this._colorGradientsTexture = null;
  59918. return this;
  59919. };
  59920. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  59921. var valueGradient = new BABYLON.FactorGradient();
  59922. valueGradient.gradient = gradient;
  59923. valueGradient.factor1 = factor;
  59924. factorGradients.push(valueGradient);
  59925. factorGradients.sort(function (a, b) {
  59926. if (a.gradient < b.gradient) {
  59927. return -1;
  59928. }
  59929. else if (a.gradient > b.gradient) {
  59930. return 1;
  59931. }
  59932. return 0;
  59933. });
  59934. this._releaseBuffers();
  59935. };
  59936. /**
  59937. * Adds a new size gradient
  59938. * @param gradient defines the gradient to use (between 0 and 1)
  59939. * @param factor defines the size factor to affect to the specified gradient
  59940. * @returns the current particle system
  59941. */
  59942. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  59943. if (!this._sizeGradients) {
  59944. this._sizeGradients = [];
  59945. }
  59946. this._addFactorGradient(this._sizeGradients, gradient, factor);
  59947. if (this._sizeGradientsTexture) {
  59948. this._sizeGradientsTexture.dispose();
  59949. this._sizeGradientsTexture = null;
  59950. }
  59951. this._releaseBuffers();
  59952. return this;
  59953. };
  59954. /**
  59955. * Remove a specific size gradient
  59956. * @param gradient defines the gradient to remove
  59957. * @returns the current particle system
  59958. */
  59959. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59960. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  59961. this._sizeGradientsTexture = null;
  59962. return this;
  59963. };
  59964. /**
  59965. * Adds a new angular speed gradient
  59966. * @param gradient defines the gradient to use (between 0 and 1)
  59967. * @param factor defines the size factor to affect to the specified gradient
  59968. * @returns the current particle system
  59969. */
  59970. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  59971. if (!this._angularSpeedGradients) {
  59972. this._angularSpeedGradients = [];
  59973. }
  59974. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  59975. if (this._angularSpeedGradientsTexture) {
  59976. this._angularSpeedGradientsTexture.dispose();
  59977. this._angularSpeedGradientsTexture = null;
  59978. }
  59979. this._releaseBuffers();
  59980. return this;
  59981. };
  59982. /**
  59983. * Remove a specific angular speed gradient
  59984. * @param gradient defines the gradient to remove
  59985. * @returns the current particle system
  59986. */
  59987. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59988. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  59989. this._angularSpeedGradientsTexture = null;
  59990. return this;
  59991. };
  59992. /**
  59993. * Adds a new velocity gradient
  59994. * @param gradient defines the gradient to use (between 0 and 1)
  59995. * @param factor defines the size factor to affect to the specified gradient
  59996. * @returns the current particle system
  59997. */
  59998. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  59999. if (!this._velocityGradients) {
  60000. this._velocityGradients = [];
  60001. }
  60002. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60003. if (this._velocityGradientsTexture) {
  60004. this._velocityGradientsTexture.dispose();
  60005. this._velocityGradientsTexture = null;
  60006. }
  60007. this._releaseBuffers();
  60008. return this;
  60009. };
  60010. /**
  60011. * Remove a specific velocity gradient
  60012. * @param gradient defines the gradient to remove
  60013. * @returns the current particle system
  60014. */
  60015. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60016. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60017. this._velocityGradientsTexture = null;
  60018. return this;
  60019. };
  60020. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60021. var updateVertexBuffers = {};
  60022. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60023. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60024. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60025. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60026. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60027. var offset = 12;
  60028. if (!this._colorGradientsTexture) {
  60029. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60030. offset += 4;
  60031. }
  60032. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60033. offset += 3;
  60034. if (!this._isBillboardBased) {
  60035. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60036. offset += 3;
  60037. }
  60038. if (this._angularSpeedGradientsTexture) {
  60039. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60040. offset += 1;
  60041. }
  60042. else {
  60043. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60044. offset += 2;
  60045. }
  60046. if (this._isAnimationSheetEnabled) {
  60047. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60048. offset += 1;
  60049. }
  60050. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60051. this._engine.bindArrayBuffer(null);
  60052. return vao;
  60053. };
  60054. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60055. var renderVertexBuffers = {};
  60056. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  60057. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  60058. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  60059. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  60060. var offset = 12;
  60061. if (!this._colorGradientsTexture) {
  60062. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  60063. offset += 4;
  60064. }
  60065. offset += 3; // Direction
  60066. if (!this._isBillboardBased) {
  60067. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  60068. offset += 3;
  60069. }
  60070. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  60071. if (this._angularSpeedGradientsTexture) {
  60072. offset++;
  60073. }
  60074. else {
  60075. offset += 2;
  60076. }
  60077. if (this._isAnimationSheetEnabled) {
  60078. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  60079. offset += 1;
  60080. }
  60081. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  60082. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  60083. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  60084. this._engine.bindArrayBuffer(null);
  60085. return vao;
  60086. };
  60087. GPUParticleSystem.prototype._initialize = function (force) {
  60088. if (force === void 0) { force = false; }
  60089. if (this._buffer0 && !force) {
  60090. return;
  60091. }
  60092. var engine = this._scene.getEngine();
  60093. var data = new Array();
  60094. if (!this.isBillboardBased) {
  60095. this._attributesStrideSize += 3;
  60096. }
  60097. if (this._colorGradientsTexture) {
  60098. this._attributesStrideSize -= 4;
  60099. }
  60100. if (this._angularSpeedGradientsTexture) {
  60101. this._attributesStrideSize -= 1;
  60102. }
  60103. if (this._isAnimationSheetEnabled) {
  60104. this._attributesStrideSize += 1;
  60105. }
  60106. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  60107. // position
  60108. data.push(0.0);
  60109. data.push(0.0);
  60110. data.push(0.0);
  60111. // Age and life
  60112. data.push(0.0); // create the particle as a dead one to create a new one at start
  60113. data.push(0.0);
  60114. // Seed
  60115. data.push(Math.random());
  60116. data.push(Math.random());
  60117. data.push(Math.random());
  60118. data.push(Math.random());
  60119. // Size
  60120. data.push(0.0);
  60121. data.push(0.0);
  60122. data.push(0.0);
  60123. if (!this._colorGradientsTexture) {
  60124. // color
  60125. data.push(0.0);
  60126. data.push(0.0);
  60127. data.push(0.0);
  60128. data.push(0.0);
  60129. }
  60130. // direction
  60131. data.push(0.0);
  60132. data.push(0.0);
  60133. data.push(0.0);
  60134. if (!this.isBillboardBased) {
  60135. // initialDirection
  60136. data.push(0.0);
  60137. data.push(0.0);
  60138. data.push(0.0);
  60139. }
  60140. // angle
  60141. data.push(0.0);
  60142. if (!this._angularSpeedGradientsTexture) {
  60143. data.push(0.0);
  60144. }
  60145. if (this._isAnimationSheetEnabled) {
  60146. data.push(0.0);
  60147. }
  60148. }
  60149. // Sprite data
  60150. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  60151. -0.5, 0.5, 0, 1,
  60152. -0.5, -0.5, 0, 0,
  60153. 0.5, -0.5, 1, 0]);
  60154. // Buffers
  60155. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60156. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  60157. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  60158. // Update VAO
  60159. this._updateVAO = [];
  60160. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  60161. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  60162. // Render VAO
  60163. this._renderVAO = [];
  60164. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  60165. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  60166. // Links
  60167. this._sourceBuffer = this._buffer0;
  60168. this._targetBuffer = this._buffer1;
  60169. };
  60170. /** @hidden */
  60171. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  60172. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  60173. if (this._isBillboardBased) {
  60174. defines += "\n#define BILLBOARD";
  60175. }
  60176. if (this._colorGradientsTexture) {
  60177. defines += "\n#define COLORGRADIENTS";
  60178. }
  60179. if (this._sizeGradientsTexture) {
  60180. defines += "\n#define SIZEGRADIENTS";
  60181. }
  60182. if (this._angularSpeedGradientsTexture) {
  60183. defines += "\n#define ANGULARSPEEDGRADIENTS";
  60184. }
  60185. if (this._velocityGradientsTexture) {
  60186. defines += "\n#define VELOCITYGRADIENTS";
  60187. }
  60188. if (this.isAnimationSheetEnabled) {
  60189. defines += "\n#define ANIMATESHEET";
  60190. }
  60191. if (this.noiseTexture) {
  60192. defines += "\n#define NOISE";
  60193. }
  60194. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  60195. return;
  60196. }
  60197. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  60198. if (!this._colorGradientsTexture) {
  60199. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  60200. }
  60201. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  60202. if (!this._isBillboardBased) {
  60203. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  60204. }
  60205. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  60206. if (this.isAnimationSheetEnabled) {
  60207. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  60208. }
  60209. this._updateEffectOptions.defines = defines;
  60210. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  60211. };
  60212. /** @hidden */
  60213. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  60214. var defines = "";
  60215. if (this._scene.clipPlane) {
  60216. defines = "\n#define CLIPPLANE";
  60217. }
  60218. if (this._isBillboardBased) {
  60219. defines += "\n#define BILLBOARD";
  60220. switch (this.billboardMode) {
  60221. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  60222. defines += "\n#define BILLBOARDY";
  60223. break;
  60224. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  60225. default:
  60226. break;
  60227. }
  60228. }
  60229. if (this._colorGradientsTexture) {
  60230. defines += "\n#define COLORGRADIENTS";
  60231. }
  60232. if (this.isAnimationSheetEnabled) {
  60233. defines += "\n#define ANIMATESHEET";
  60234. }
  60235. if (this._renderEffect && this._renderEffect.defines === defines) {
  60236. return;
  60237. }
  60238. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  60239. };
  60240. /**
  60241. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60242. * @param preWarm defines if we are in the pre-warmimg phase
  60243. */
  60244. GPUParticleSystem.prototype.animate = function (preWarm) {
  60245. if (preWarm === void 0) { preWarm = false; }
  60246. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60247. this._actualFrame += this._timeDelta;
  60248. if (!this._stopped) {
  60249. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  60250. this.stop();
  60251. }
  60252. }
  60253. };
  60254. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  60255. var texture = this[textureName];
  60256. if (!factorGradients || !factorGradients.length || texture) {
  60257. return;
  60258. }
  60259. var data = new Float32Array(this._rawTextureWidth);
  60260. for (var x = 0; x < this._rawTextureWidth; x++) {
  60261. var ratio = x / this._rawTextureWidth;
  60262. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  60263. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  60264. });
  60265. }
  60266. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60267. };
  60268. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  60269. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  60270. };
  60271. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  60272. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  60273. };
  60274. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  60275. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  60276. };
  60277. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  60278. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  60279. return;
  60280. }
  60281. var data = new Uint8Array(this._rawTextureWidth * 4);
  60282. var tmpColor = BABYLON.Tmp.Color4[0];
  60283. for (var x = 0; x < this._rawTextureWidth; x++) {
  60284. var ratio = x / this._rawTextureWidth;
  60285. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  60286. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  60287. data[x * 4] = tmpColor.r * 255;
  60288. data[x * 4 + 1] = tmpColor.g * 255;
  60289. data[x * 4 + 2] = tmpColor.b * 255;
  60290. data[x * 4 + 3] = tmpColor.a * 255;
  60291. });
  60292. }
  60293. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60294. };
  60295. /**
  60296. * Renders the particle system in its current state
  60297. * @param preWarm defines if the system should only update the particles but not render them
  60298. * @returns the current number of particles
  60299. */
  60300. GPUParticleSystem.prototype.render = function (preWarm) {
  60301. if (preWarm === void 0) { preWarm = false; }
  60302. if (!this._started) {
  60303. return 0;
  60304. }
  60305. this._createColorGradientTexture();
  60306. this._createSizeGradientTexture();
  60307. this._createAngularSpeedGradientTexture();
  60308. this._createVelocityGradientTexture();
  60309. this._recreateUpdateEffect();
  60310. this._recreateRenderEffect();
  60311. if (!this.isReady()) {
  60312. return 0;
  60313. }
  60314. if (!preWarm) {
  60315. if (!this._preWarmDone && this.preWarmCycles) {
  60316. for (var index = 0; index < this.preWarmCycles; index++) {
  60317. this.animate(true);
  60318. this.render(true);
  60319. }
  60320. this._preWarmDone = true;
  60321. }
  60322. if (this._currentRenderId === this._scene.getRenderId()) {
  60323. return 0;
  60324. }
  60325. this._currentRenderId = this._scene.getRenderId();
  60326. }
  60327. // Get everything ready to render
  60328. this._initialize();
  60329. this._accumulatedCount += this.emitRate * this._timeDelta;
  60330. if (this._accumulatedCount > 1) {
  60331. var intPart = this._accumulatedCount | 0;
  60332. this._accumulatedCount -= intPart;
  60333. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  60334. }
  60335. if (!this._currentActiveCount) {
  60336. return 0;
  60337. }
  60338. // Enable update effect
  60339. this._engine.enableEffect(this._updateEffect);
  60340. this._engine.setState(false);
  60341. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  60342. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  60343. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  60344. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  60345. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  60346. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  60347. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  60348. if (!this._colorGradientsTexture) {
  60349. this._updateEffect.setDirectColor4("color1", this.color1);
  60350. this._updateEffect.setDirectColor4("color2", this.color2);
  60351. }
  60352. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  60353. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  60354. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  60355. this._updateEffect.setVector3("gravity", this.gravity);
  60356. if (this._sizeGradientsTexture) {
  60357. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  60358. }
  60359. if (this._angularSpeedGradientsTexture) {
  60360. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  60361. }
  60362. if (this._velocityGradientsTexture) {
  60363. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  60364. }
  60365. if (this.particleEmitterType) {
  60366. this.particleEmitterType.applyToShader(this._updateEffect);
  60367. }
  60368. if (this._isAnimationSheetEnabled) {
  60369. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  60370. }
  60371. if (this.noiseTexture) {
  60372. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  60373. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  60374. }
  60375. var emitterWM;
  60376. if (this.emitter.position) {
  60377. var emitterMesh = this.emitter;
  60378. emitterWM = emitterMesh.getWorldMatrix();
  60379. }
  60380. else {
  60381. var emitterPosition = this.emitter;
  60382. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  60383. }
  60384. this._updateEffect.setMatrix("emitterWM", emitterWM);
  60385. // Bind source VAO
  60386. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  60387. // Update
  60388. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  60389. this._engine.setRasterizerState(false);
  60390. this._engine.beginTransformFeedback(true);
  60391. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  60392. this._engine.endTransformFeedback();
  60393. this._engine.setRasterizerState(true);
  60394. this._engine.bindTransformFeedbackBuffer(null);
  60395. if (!preWarm) {
  60396. // Enable render effect
  60397. this._engine.enableEffect(this._renderEffect);
  60398. var viewMatrix = this._scene.getViewMatrix();
  60399. this._renderEffect.setMatrix("view", viewMatrix);
  60400. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  60401. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  60402. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  60403. if (this._colorGradientsTexture) {
  60404. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  60405. }
  60406. else {
  60407. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  60408. }
  60409. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60410. var baseSize = this.particleTexture.getBaseSize();
  60411. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60412. }
  60413. if (this._isBillboardBased) {
  60414. var camera = this._scene.activeCamera;
  60415. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  60416. }
  60417. if (this._scene.clipPlane) {
  60418. var clipPlane = this._scene.clipPlane;
  60419. var invView = viewMatrix.clone();
  60420. invView.invert();
  60421. this._renderEffect.setMatrix("invView", invView);
  60422. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  60423. }
  60424. // Draw order
  60425. switch (this.blendMode) {
  60426. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  60427. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60428. break;
  60429. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  60430. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60431. break;
  60432. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  60433. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60434. break;
  60435. }
  60436. if (this.forceDepthWrite) {
  60437. this._engine.setDepthWrite(true);
  60438. }
  60439. // Bind source VAO
  60440. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  60441. // Render
  60442. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  60443. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60444. }
  60445. // Switch VAOs
  60446. this._targetIndex++;
  60447. if (this._targetIndex === 2) {
  60448. this._targetIndex = 0;
  60449. }
  60450. // Switch buffers
  60451. var tmpBuffer = this._sourceBuffer;
  60452. this._sourceBuffer = this._targetBuffer;
  60453. this._targetBuffer = tmpBuffer;
  60454. return this._currentActiveCount;
  60455. };
  60456. /**
  60457. * Rebuilds the particle system
  60458. */
  60459. GPUParticleSystem.prototype.rebuild = function () {
  60460. this._initialize(true);
  60461. };
  60462. GPUParticleSystem.prototype._releaseBuffers = function () {
  60463. if (this._buffer0) {
  60464. this._buffer0.dispose();
  60465. this._buffer0 = null;
  60466. }
  60467. if (this._buffer1) {
  60468. this._buffer1.dispose();
  60469. this._buffer1 = null;
  60470. }
  60471. if (this._spriteBuffer) {
  60472. this._spriteBuffer.dispose();
  60473. this._spriteBuffer = null;
  60474. }
  60475. };
  60476. GPUParticleSystem.prototype._releaseVAOs = function () {
  60477. if (!this._updateVAO) {
  60478. return;
  60479. }
  60480. for (var index = 0; index < this._updateVAO.length; index++) {
  60481. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  60482. }
  60483. this._updateVAO = [];
  60484. for (var index = 0; index < this._renderVAO.length; index++) {
  60485. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  60486. }
  60487. this._renderVAO = [];
  60488. };
  60489. /**
  60490. * Disposes the particle system and free the associated resources
  60491. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60492. */
  60493. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  60494. if (disposeTexture === void 0) { disposeTexture = true; }
  60495. var index = this._scene.particleSystems.indexOf(this);
  60496. if (index > -1) {
  60497. this._scene.particleSystems.splice(index, 1);
  60498. }
  60499. this._releaseBuffers();
  60500. this._releaseVAOs();
  60501. if (this._colorGradientsTexture) {
  60502. this._colorGradientsTexture.dispose();
  60503. this._colorGradientsTexture = null;
  60504. }
  60505. if (this._sizeGradientsTexture) {
  60506. this._sizeGradientsTexture.dispose();
  60507. this._sizeGradientsTexture = null;
  60508. }
  60509. if (this._angularSpeedGradientsTexture) {
  60510. this._angularSpeedGradientsTexture.dispose();
  60511. this._angularSpeedGradientsTexture = null;
  60512. }
  60513. if (this._velocityGradientsTexture) {
  60514. this._velocityGradientsTexture.dispose();
  60515. this._velocityGradientsTexture = null;
  60516. }
  60517. if (this._randomTexture) {
  60518. this._randomTexture.dispose();
  60519. this._randomTexture = null;
  60520. }
  60521. if (this._randomTexture2) {
  60522. this._randomTexture2.dispose();
  60523. this._randomTexture2 = null;
  60524. }
  60525. if (disposeTexture && this.particleTexture) {
  60526. this.particleTexture.dispose();
  60527. this.particleTexture = null;
  60528. }
  60529. if (disposeTexture && this.noiseTexture) {
  60530. this.noiseTexture.dispose();
  60531. this.noiseTexture = null;
  60532. }
  60533. // Callback
  60534. this.onDisposeObservable.notifyObservers(this);
  60535. this.onDisposeObservable.clear();
  60536. };
  60537. /**
  60538. * Clones the particle system.
  60539. * @param name The name of the cloned object
  60540. * @param newEmitter The new emitter to use
  60541. * @returns the cloned particle system
  60542. */
  60543. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  60544. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  60545. BABYLON.Tools.DeepCopy(this, result);
  60546. if (newEmitter === undefined) {
  60547. newEmitter = this.emitter;
  60548. }
  60549. result.emitter = newEmitter;
  60550. if (this.particleTexture) {
  60551. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60552. }
  60553. return result;
  60554. };
  60555. /**
  60556. * Serializes the particle system to a JSON object.
  60557. * @returns the JSON object
  60558. */
  60559. GPUParticleSystem.prototype.serialize = function () {
  60560. var serializationObject = {};
  60561. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  60562. serializationObject.activeParticleCount = this.activeParticleCount;
  60563. return serializationObject;
  60564. };
  60565. /**
  60566. * Parses a JSON object to create a GPU particle system.
  60567. * @param parsedParticleSystem The JSON object to parse
  60568. * @param scene The scene to create the particle system in
  60569. * @param rootUrl The root url to use to load external dependencies like texture
  60570. * @returns the parsed GPU particle system
  60571. */
  60572. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  60573. var name = parsedParticleSystem.name;
  60574. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  60575. if (parsedParticleSystem.activeParticleCount) {
  60576. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  60577. }
  60578. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  60579. return particleSystem;
  60580. };
  60581. return GPUParticleSystem;
  60582. }());
  60583. BABYLON.GPUParticleSystem = GPUParticleSystem;
  60584. })(BABYLON || (BABYLON = {}));
  60585. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  60586. var BABYLON;
  60587. (function (BABYLON) {
  60588. /**
  60589. * Represents one particle of a solid particle system.
  60590. */
  60591. var SolidParticle = /** @class */ (function () {
  60592. /**
  60593. * Creates a Solid Particle object.
  60594. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  60595. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  60596. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  60597. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  60598. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  60599. * @param shapeId (integer) is the model shape identifier in the SPS.
  60600. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  60601. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  60602. */
  60603. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  60604. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  60605. /**
  60606. * particle global index
  60607. */
  60608. this.idx = 0;
  60609. /**
  60610. * The color of the particle
  60611. */
  60612. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60613. /**
  60614. * The world space position of the particle.
  60615. */
  60616. this.position = BABYLON.Vector3.Zero();
  60617. /**
  60618. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  60619. */
  60620. this.rotation = BABYLON.Vector3.Zero();
  60621. /**
  60622. * The scaling of the particle.
  60623. */
  60624. this.scaling = BABYLON.Vector3.One();
  60625. /**
  60626. * The uvs of the particle.
  60627. */
  60628. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  60629. /**
  60630. * The current speed of the particle.
  60631. */
  60632. this.velocity = BABYLON.Vector3.Zero();
  60633. /**
  60634. * The pivot point in the particle local space.
  60635. */
  60636. this.pivot = BABYLON.Vector3.Zero();
  60637. /**
  60638. * Must the particle be translated from its pivot point in its local space ?
  60639. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  60640. * Default : false
  60641. */
  60642. this.translateFromPivot = false;
  60643. /**
  60644. * Is the particle active or not ?
  60645. */
  60646. this.alive = true;
  60647. /**
  60648. * Is the particle visible or not ?
  60649. */
  60650. this.isVisible = true;
  60651. /**
  60652. * Index of this particle in the global "positions" array (Internal use)
  60653. */
  60654. this._pos = 0;
  60655. /**
  60656. * Index of this particle in the global "indices" array (Internal use)
  60657. */
  60658. this._ind = 0;
  60659. /**
  60660. * ModelShape id of this particle
  60661. */
  60662. this.shapeId = 0;
  60663. /**
  60664. * Index of the particle in its shape id (Internal use)
  60665. */
  60666. this.idxInShape = 0;
  60667. /**
  60668. * Still set as invisible in order to skip useless computations (Internal use)
  60669. */
  60670. this._stillInvisible = false;
  60671. /**
  60672. * Last computed particle rotation matrix
  60673. */
  60674. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  60675. /**
  60676. * Parent particle Id, if any.
  60677. * Default null.
  60678. */
  60679. this.parentId = null;
  60680. /**
  60681. * Internal global position in the SPS.
  60682. */
  60683. this._globalPosition = BABYLON.Vector3.Zero();
  60684. this.idx = particleIndex;
  60685. this._pos = positionIndex;
  60686. this._ind = indiceIndex;
  60687. this._model = model;
  60688. this.shapeId = shapeId;
  60689. this.idxInShape = idxInShape;
  60690. this._sps = sps;
  60691. if (modelBoundingInfo) {
  60692. this._modelBoundingInfo = modelBoundingInfo;
  60693. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  60694. }
  60695. }
  60696. Object.defineProperty(SolidParticle.prototype, "scale", {
  60697. /**
  60698. * Legacy support, changed scale to scaling
  60699. */
  60700. get: function () {
  60701. return this.scaling;
  60702. },
  60703. /**
  60704. * Legacy support, changed scale to scaling
  60705. */
  60706. set: function (scale) {
  60707. this.scaling = scale;
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  60713. /**
  60714. * Legacy support, changed quaternion to rotationQuaternion
  60715. */
  60716. get: function () {
  60717. return this.rotationQuaternion;
  60718. },
  60719. /**
  60720. * Legacy support, changed quaternion to rotationQuaternion
  60721. */
  60722. set: function (q) {
  60723. this.rotationQuaternion = q;
  60724. },
  60725. enumerable: true,
  60726. configurable: true
  60727. });
  60728. /**
  60729. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  60730. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  60731. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  60732. * @returns true if it intersects
  60733. */
  60734. SolidParticle.prototype.intersectsMesh = function (target) {
  60735. if (!this._boundingInfo || !target._boundingInfo) {
  60736. return false;
  60737. }
  60738. if (this._sps._bSphereOnly) {
  60739. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  60740. }
  60741. return this._boundingInfo.intersects(target._boundingInfo, false);
  60742. };
  60743. return SolidParticle;
  60744. }());
  60745. BABYLON.SolidParticle = SolidParticle;
  60746. /**
  60747. * Represents the shape of the model used by one particle of a solid particle system.
  60748. * SPS internal tool, don't use it manually.
  60749. */
  60750. var ModelShape = /** @class */ (function () {
  60751. /**
  60752. * 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.
  60753. * SPS internal tool, don't use it manually.
  60754. * @hidden
  60755. */
  60756. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  60757. /**
  60758. * length of the shape in the model indices array (internal use)
  60759. */
  60760. this._indicesLength = 0;
  60761. this.shapeID = id;
  60762. this._shape = shape;
  60763. this._indicesLength = indicesLength;
  60764. this._shapeUV = shapeUV;
  60765. this._positionFunction = posFunction;
  60766. this._vertexFunction = vtxFunction;
  60767. }
  60768. return ModelShape;
  60769. }());
  60770. BABYLON.ModelShape = ModelShape;
  60771. /**
  60772. * Represents a Depth Sorted Particle in the solid particle system.
  60773. */
  60774. var DepthSortedParticle = /** @class */ (function () {
  60775. function DepthSortedParticle() {
  60776. /**
  60777. * Index of the particle in the "indices" array
  60778. */
  60779. this.ind = 0;
  60780. /**
  60781. * Length of the particle shape in the "indices" array
  60782. */
  60783. this.indicesLength = 0;
  60784. /**
  60785. * Squared distance from the particle to the camera
  60786. */
  60787. this.sqDistance = 0.0;
  60788. }
  60789. return DepthSortedParticle;
  60790. }());
  60791. BABYLON.DepthSortedParticle = DepthSortedParticle;
  60792. })(BABYLON || (BABYLON = {}));
  60793. //# sourceMappingURL=babylon.solidParticle.js.map
  60794. var BABYLON;
  60795. (function (BABYLON) {
  60796. /**
  60797. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  60798. *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.
  60799. * The SPS is also a particle system. It provides some methods to manage the particles.
  60800. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  60801. *
  60802. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  60803. */
  60804. var SolidParticleSystem = /** @class */ (function () {
  60805. /**
  60806. * Creates a SPS (Solid Particle System) object.
  60807. * @param name (String) is the SPS name, this will be the underlying mesh name.
  60808. * @param scene (Scene) is the scene in which the SPS is added.
  60809. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  60810. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  60811. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  60812. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  60813. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  60814. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  60815. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  60816. */
  60817. function SolidParticleSystem(name, scene, options) {
  60818. /**
  60819. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  60820. * Example : var p = SPS.particles[i];
  60821. */
  60822. this.particles = new Array();
  60823. /**
  60824. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  60825. */
  60826. this.nbParticles = 0;
  60827. /**
  60828. * If the particles must ever face the camera (default false). Useful for planar particles.
  60829. */
  60830. this.billboard = false;
  60831. /**
  60832. * Recompute normals when adding a shape
  60833. */
  60834. this.recomputeNormals = true;
  60835. /**
  60836. * This a counter ofr your own usage. It's not set by any SPS functions.
  60837. */
  60838. this.counter = 0;
  60839. /**
  60840. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  60841. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  60842. */
  60843. this.vars = {};
  60844. /**
  60845. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  60846. */
  60847. this._bSphereOnly = false;
  60848. /**
  60849. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  60850. */
  60851. this._bSphereRadiusFactor = 1.0;
  60852. this._positions = new Array();
  60853. this._indices = new Array();
  60854. this._normals = new Array();
  60855. this._colors = new Array();
  60856. this._uvs = new Array();
  60857. this._index = 0; // indices index
  60858. this._updatable = true;
  60859. this._pickable = false;
  60860. this._isVisibilityBoxLocked = false;
  60861. this._alwaysVisible = false;
  60862. this._depthSort = false;
  60863. this._shapeCounter = 0;
  60864. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  60865. this._color = new BABYLON.Color4(0, 0, 0, 0);
  60866. this._computeParticleColor = true;
  60867. this._computeParticleTexture = true;
  60868. this._computeParticleRotation = true;
  60869. this._computeParticleVertex = false;
  60870. this._computeBoundingBox = false;
  60871. this._depthSortParticles = true;
  60872. this._cam_axisZ = BABYLON.Vector3.Zero();
  60873. this._cam_axisY = BABYLON.Vector3.Zero();
  60874. this._cam_axisX = BABYLON.Vector3.Zero();
  60875. this._axisZ = BABYLON.Axis.Z;
  60876. this._camDir = BABYLON.Vector3.Zero();
  60877. this._camInvertedPosition = BABYLON.Vector3.Zero();
  60878. this._rotMatrix = new BABYLON.Matrix();
  60879. this._invertMatrix = new BABYLON.Matrix();
  60880. this._rotated = BABYLON.Vector3.Zero();
  60881. this._quaternion = new BABYLON.Quaternion();
  60882. this._vertex = BABYLON.Vector3.Zero();
  60883. this._normal = BABYLON.Vector3.Zero();
  60884. this._yaw = 0.0;
  60885. this._pitch = 0.0;
  60886. this._roll = 0.0;
  60887. this._halfroll = 0.0;
  60888. this._halfpitch = 0.0;
  60889. this._halfyaw = 0.0;
  60890. this._sinRoll = 0.0;
  60891. this._cosRoll = 0.0;
  60892. this._sinPitch = 0.0;
  60893. this._cosPitch = 0.0;
  60894. this._sinYaw = 0.0;
  60895. this._cosYaw = 0.0;
  60896. this._mustUnrotateFixedNormals = false;
  60897. this._minimum = BABYLON.Vector3.Zero();
  60898. this._maximum = BABYLON.Vector3.Zero();
  60899. this._minBbox = BABYLON.Vector3.Zero();
  60900. this._maxBbox = BABYLON.Vector3.Zero();
  60901. this._particlesIntersect = false;
  60902. this._depthSortFunction = function (p1, p2) {
  60903. return (p2.sqDistance - p1.sqDistance);
  60904. };
  60905. this._needs32Bits = false;
  60906. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  60907. this._scaledPivot = BABYLON.Vector3.Zero();
  60908. this._particleHasParent = false;
  60909. this.name = name;
  60910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60911. this._camera = scene.activeCamera;
  60912. this._pickable = options ? options.isPickable : false;
  60913. this._depthSort = options ? options.enableDepthSort : false;
  60914. this._particlesIntersect = options ? options.particleIntersection : false;
  60915. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  60916. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  60917. if (options && options.updatable !== undefined) {
  60918. this._updatable = options.updatable;
  60919. }
  60920. else {
  60921. this._updatable = true;
  60922. }
  60923. if (this._pickable) {
  60924. this.pickedParticles = [];
  60925. }
  60926. if (this._depthSort) {
  60927. this.depthSortedParticles = [];
  60928. }
  60929. }
  60930. /**
  60931. * Builds the SPS underlying mesh. Returns a standard Mesh.
  60932. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  60933. * @returns the created mesh
  60934. */
  60935. SolidParticleSystem.prototype.buildMesh = function () {
  60936. if (this.nbParticles === 0) {
  60937. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  60938. this.addShape(triangle, 1);
  60939. triangle.dispose();
  60940. }
  60941. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  60942. this._positions32 = new Float32Array(this._positions);
  60943. this._uvs32 = new Float32Array(this._uvs);
  60944. this._colors32 = new Float32Array(this._colors);
  60945. if (this.recomputeNormals) {
  60946. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  60947. }
  60948. this._normals32 = new Float32Array(this._normals);
  60949. this._fixedNormal32 = new Float32Array(this._normals);
  60950. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  60951. this._unrotateFixedNormals();
  60952. }
  60953. var vertexData = new BABYLON.VertexData();
  60954. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  60955. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  60956. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  60957. if (this._uvs32.length > 0) {
  60958. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  60959. }
  60960. if (this._colors32.length > 0) {
  60961. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  60962. }
  60963. var mesh = new BABYLON.Mesh(this.name, this._scene);
  60964. vertexData.applyToMesh(mesh, this._updatable);
  60965. this.mesh = mesh;
  60966. this.mesh.isPickable = this._pickable;
  60967. // free memory
  60968. if (!this._depthSort) {
  60969. this._indices = null;
  60970. }
  60971. this._positions = null;
  60972. this._normals = null;
  60973. this._uvs = null;
  60974. this._colors = null;
  60975. if (!this._updatable) {
  60976. this.particles.length = 0;
  60977. }
  60978. return mesh;
  60979. };
  60980. /**
  60981. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  60982. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  60983. * Thus the particles generated from `digest()` have their property `position` set yet.
  60984. * @param mesh ( Mesh ) is the mesh to be digested
  60985. * @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
  60986. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  60987. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  60988. * @returns the current SPS
  60989. */
  60990. SolidParticleSystem.prototype.digest = function (mesh, options) {
  60991. var size = (options && options.facetNb) || 1;
  60992. var number = (options && options.number) || 0;
  60993. var delta = (options && options.delta) || 0;
  60994. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60995. var meshInd = mesh.getIndices();
  60996. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60997. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60998. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60999. var f = 0; // facet counter
  61000. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61001. // compute size from number
  61002. if (number) {
  61003. number = (number > totalFacets) ? totalFacets : number;
  61004. size = Math.round(totalFacets / number);
  61005. delta = 0;
  61006. }
  61007. else {
  61008. size = (size > totalFacets) ? totalFacets : size;
  61009. }
  61010. var facetPos = []; // submesh positions
  61011. var facetInd = []; // submesh indices
  61012. var facetUV = []; // submesh UV
  61013. var facetCol = []; // submesh colors
  61014. var barycenter = BABYLON.Vector3.Zero();
  61015. var sizeO = size;
  61016. while (f < totalFacets) {
  61017. size = sizeO + Math.floor((1 + delta) * Math.random());
  61018. if (f > totalFacets - size) {
  61019. size = totalFacets - f;
  61020. }
  61021. // reset temp arrays
  61022. facetPos.length = 0;
  61023. facetInd.length = 0;
  61024. facetUV.length = 0;
  61025. facetCol.length = 0;
  61026. // iterate over "size" facets
  61027. var fi = 0;
  61028. for (var j = f * 3; j < (f + size) * 3; j++) {
  61029. facetInd.push(fi);
  61030. var i = meshInd[j];
  61031. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  61032. if (meshUV) {
  61033. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  61034. }
  61035. if (meshCol) {
  61036. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  61037. }
  61038. fi++;
  61039. }
  61040. // create a model shape for each single particle
  61041. var idx = this.nbParticles;
  61042. var shape = this._posToShape(facetPos);
  61043. var shapeUV = this._uvsToShapeUV(facetUV);
  61044. // compute the barycenter of the shape
  61045. var v;
  61046. for (v = 0; v < shape.length; v++) {
  61047. barycenter.addInPlace(shape[v]);
  61048. }
  61049. barycenter.scaleInPlace(1 / shape.length);
  61050. // shift the shape from its barycenter to the origin
  61051. for (v = 0; v < shape.length; v++) {
  61052. shape[v].subtractInPlace(barycenter);
  61053. }
  61054. var bInfo;
  61055. if (this._particlesIntersect) {
  61056. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  61057. }
  61058. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  61059. // add the particle in the SPS
  61060. var currentPos = this._positions.length;
  61061. var currentInd = this._indices.length;
  61062. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  61063. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  61064. // initialize the particle position
  61065. this.particles[this.nbParticles].position.addInPlace(barycenter);
  61066. this._index += shape.length;
  61067. idx++;
  61068. this.nbParticles++;
  61069. this._shapeCounter++;
  61070. f += size;
  61071. }
  61072. return this;
  61073. };
  61074. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  61075. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  61076. var index = 0;
  61077. var idx = 0;
  61078. for (var p = 0; p < this.particles.length; p++) {
  61079. this._particle = this.particles[p];
  61080. this._shape = this._particle._model._shape;
  61081. if (this._particle.rotationQuaternion) {
  61082. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61083. }
  61084. else {
  61085. this._yaw = this._particle.rotation.y;
  61086. this._pitch = this._particle.rotation.x;
  61087. this._roll = this._particle.rotation.z;
  61088. this._quaternionRotationYPR();
  61089. }
  61090. this._quaternionToRotationMatrix();
  61091. this._rotMatrix.invertToRef(this._invertMatrix);
  61092. for (var pt = 0; pt < this._shape.length; pt++) {
  61093. idx = index + pt * 3;
  61094. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  61095. this._fixedNormal32[idx] = this._normal.x;
  61096. this._fixedNormal32[idx + 1] = this._normal.y;
  61097. this._fixedNormal32[idx + 2] = this._normal.z;
  61098. }
  61099. index = idx + 3;
  61100. }
  61101. };
  61102. //reset copy
  61103. SolidParticleSystem.prototype._resetCopy = function () {
  61104. this._copy.position.x = 0;
  61105. this._copy.position.y = 0;
  61106. this._copy.position.z = 0;
  61107. this._copy.rotation.x = 0;
  61108. this._copy.rotation.y = 0;
  61109. this._copy.rotation.z = 0;
  61110. this._copy.rotationQuaternion = null;
  61111. this._copy.scaling.x = 1.0;
  61112. this._copy.scaling.y = 1.0;
  61113. this._copy.scaling.z = 1.0;
  61114. this._copy.uvs.x = 0;
  61115. this._copy.uvs.y = 0;
  61116. this._copy.uvs.z = 1.0;
  61117. this._copy.uvs.w = 1.0;
  61118. this._copy.color = null;
  61119. this._copy.translateFromPivot = false;
  61120. };
  61121. // _meshBuilder : inserts the shape model in the global SPS mesh
  61122. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  61123. var i;
  61124. var u = 0;
  61125. var c = 0;
  61126. var n = 0;
  61127. this._resetCopy();
  61128. if (options && options.positionFunction) { // call to custom positionFunction
  61129. options.positionFunction(this._copy, idx, idxInShape);
  61130. this._mustUnrotateFixedNormals = true;
  61131. }
  61132. if (this._copy.rotationQuaternion) {
  61133. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61134. }
  61135. else {
  61136. this._yaw = this._copy.rotation.y;
  61137. this._pitch = this._copy.rotation.x;
  61138. this._roll = this._copy.rotation.z;
  61139. this._quaternionRotationYPR();
  61140. }
  61141. this._quaternionToRotationMatrix();
  61142. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  61143. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  61144. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  61145. if (this._copy.translateFromPivot) {
  61146. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61147. }
  61148. else {
  61149. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61150. }
  61151. for (i = 0; i < shape.length; i++) {
  61152. this._vertex.x = shape[i].x;
  61153. this._vertex.y = shape[i].y;
  61154. this._vertex.z = shape[i].z;
  61155. if (options && options.vertexFunction) {
  61156. options.vertexFunction(this._copy, this._vertex, i);
  61157. }
  61158. this._vertex.x *= this._copy.scaling.x;
  61159. this._vertex.y *= this._copy.scaling.y;
  61160. this._vertex.z *= this._copy.scaling.z;
  61161. this._vertex.x -= this._scaledPivot.x;
  61162. this._vertex.y -= this._scaledPivot.y;
  61163. this._vertex.z -= this._scaledPivot.z;
  61164. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61165. this._rotated.addInPlace(this._pivotBackTranslation);
  61166. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  61167. if (meshUV) {
  61168. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  61169. u += 2;
  61170. }
  61171. if (this._copy.color) {
  61172. this._color = this._copy.color;
  61173. }
  61174. else if (meshCol && meshCol[c] !== undefined) {
  61175. this._color.r = meshCol[c];
  61176. this._color.g = meshCol[c + 1];
  61177. this._color.b = meshCol[c + 2];
  61178. this._color.a = meshCol[c + 3];
  61179. }
  61180. else {
  61181. this._color.r = 1.0;
  61182. this._color.g = 1.0;
  61183. this._color.b = 1.0;
  61184. this._color.a = 1.0;
  61185. }
  61186. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  61187. c += 4;
  61188. if (!this.recomputeNormals && meshNor) {
  61189. this._normal.x = meshNor[n];
  61190. this._normal.y = meshNor[n + 1];
  61191. this._normal.z = meshNor[n + 2];
  61192. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  61193. normals.push(this._normal.x, this._normal.y, this._normal.z);
  61194. n += 3;
  61195. }
  61196. }
  61197. for (i = 0; i < meshInd.length; i++) {
  61198. var current_ind = p + meshInd[i];
  61199. indices.push(current_ind);
  61200. if (current_ind > 65535) {
  61201. this._needs32Bits = true;
  61202. }
  61203. }
  61204. if (this._pickable) {
  61205. var nbfaces = meshInd.length / 3;
  61206. for (i = 0; i < nbfaces; i++) {
  61207. this.pickedParticles.push({ idx: idx, faceId: i });
  61208. }
  61209. }
  61210. if (this._depthSort) {
  61211. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  61212. }
  61213. return this._copy;
  61214. };
  61215. // returns a shape array from positions array
  61216. SolidParticleSystem.prototype._posToShape = function (positions) {
  61217. var shape = [];
  61218. for (var i = 0; i < positions.length; i += 3) {
  61219. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  61220. }
  61221. return shape;
  61222. };
  61223. // returns a shapeUV array from a Vector4 uvs
  61224. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  61225. var shapeUV = [];
  61226. if (uvs) {
  61227. for (var i = 0; i < uvs.length; i++)
  61228. shapeUV.push(uvs[i]);
  61229. }
  61230. return shapeUV;
  61231. };
  61232. // adds a new particle object in the particles array
  61233. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  61234. if (bInfo === void 0) { bInfo = null; }
  61235. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  61236. this.particles.push(sp);
  61237. return sp;
  61238. };
  61239. /**
  61240. * Adds some particles to the SPS from the model shape. Returns the shape id.
  61241. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  61242. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  61243. * @param nb (positive integer) the number of particles to be created from this model
  61244. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  61245. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  61246. * @returns the number of shapes in the system
  61247. */
  61248. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  61249. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61250. var meshInd = mesh.getIndices();
  61251. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61252. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61253. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61254. var bbInfo;
  61255. if (this._particlesIntersect) {
  61256. bbInfo = mesh.getBoundingInfo();
  61257. }
  61258. var shape = this._posToShape(meshPos);
  61259. var shapeUV = this._uvsToShapeUV(meshUV);
  61260. var posfunc = options ? options.positionFunction : null;
  61261. var vtxfunc = options ? options.vertexFunction : null;
  61262. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  61263. // particles
  61264. var sp;
  61265. var currentCopy;
  61266. var idx = this.nbParticles;
  61267. for (var i = 0; i < nb; i++) {
  61268. var currentPos = this._positions.length;
  61269. var currentInd = this._indices.length;
  61270. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  61271. if (this._updatable) {
  61272. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  61273. sp.position.copyFrom(currentCopy.position);
  61274. sp.rotation.copyFrom(currentCopy.rotation);
  61275. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  61276. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  61277. }
  61278. if (currentCopy.color && sp.color) {
  61279. sp.color.copyFrom(currentCopy.color);
  61280. }
  61281. sp.scaling.copyFrom(currentCopy.scaling);
  61282. sp.uvs.copyFrom(currentCopy.uvs);
  61283. }
  61284. this._index += shape.length;
  61285. idx++;
  61286. }
  61287. this.nbParticles += nb;
  61288. this._shapeCounter++;
  61289. return this._shapeCounter - 1;
  61290. };
  61291. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  61292. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  61293. this._resetCopy();
  61294. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  61295. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  61296. }
  61297. if (this._copy.rotationQuaternion) {
  61298. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  61299. }
  61300. else {
  61301. this._yaw = this._copy.rotation.y;
  61302. this._pitch = this._copy.rotation.x;
  61303. this._roll = this._copy.rotation.z;
  61304. this._quaternionRotationYPR();
  61305. }
  61306. this._quaternionToRotationMatrix();
  61307. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61308. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61309. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61310. if (this._copy.translateFromPivot) {
  61311. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  61312. }
  61313. else {
  61314. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  61315. }
  61316. this._shape = particle._model._shape;
  61317. for (var pt = 0; pt < this._shape.length; pt++) {
  61318. this._vertex.x = this._shape[pt].x;
  61319. this._vertex.y = this._shape[pt].y;
  61320. this._vertex.z = this._shape[pt].z;
  61321. if (particle._model._vertexFunction) {
  61322. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  61323. }
  61324. this._vertex.x *= this._copy.scaling.x;
  61325. this._vertex.y *= this._copy.scaling.y;
  61326. this._vertex.z *= this._copy.scaling.z;
  61327. this._vertex.x -= this._scaledPivot.x;
  61328. this._vertex.y -= this._scaledPivot.y;
  61329. this._vertex.z -= this._scaledPivot.z;
  61330. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  61331. this._rotated.addInPlace(this._pivotBackTranslation);
  61332. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  61333. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  61334. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  61335. }
  61336. particle.position.x = 0.0;
  61337. particle.position.y = 0.0;
  61338. particle.position.z = 0.0;
  61339. particle.rotation.x = 0.0;
  61340. particle.rotation.y = 0.0;
  61341. particle.rotation.z = 0.0;
  61342. particle.rotationQuaternion = null;
  61343. particle.scaling.x = 1.0;
  61344. particle.scaling.y = 1.0;
  61345. particle.scaling.z = 1.0;
  61346. particle.uvs.x = 0.0;
  61347. particle.uvs.y = 0.0;
  61348. particle.uvs.z = 1.0;
  61349. particle.uvs.w = 1.0;
  61350. particle.pivot.x = 0.0;
  61351. particle.pivot.y = 0.0;
  61352. particle.pivot.z = 0.0;
  61353. particle.translateFromPivot = false;
  61354. particle.parentId = null;
  61355. };
  61356. /**
  61357. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  61358. * @returns the SPS.
  61359. */
  61360. SolidParticleSystem.prototype.rebuildMesh = function () {
  61361. for (var p = 0; p < this.particles.length; p++) {
  61362. this._rebuildParticle(this.particles[p]);
  61363. }
  61364. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61365. return this;
  61366. };
  61367. /**
  61368. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  61369. * This method calls `updateParticle()` for each particle of the SPS.
  61370. * For an animated SPS, it is usually called within the render loop.
  61371. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  61372. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  61373. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  61374. * @returns the SPS.
  61375. */
  61376. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  61377. if (start === void 0) { start = 0; }
  61378. if (end === void 0) { end = this.nbParticles - 1; }
  61379. if (update === void 0) { update = true; }
  61380. if (!this._updatable) {
  61381. return this;
  61382. }
  61383. // custom beforeUpdate
  61384. this.beforeUpdateParticles(start, end, update);
  61385. this._cam_axisX.x = 1.0;
  61386. this._cam_axisX.y = 0.0;
  61387. this._cam_axisX.z = 0.0;
  61388. this._cam_axisY.x = 0.0;
  61389. this._cam_axisY.y = 1.0;
  61390. this._cam_axisY.z = 0.0;
  61391. this._cam_axisZ.x = 0.0;
  61392. this._cam_axisZ.y = 0.0;
  61393. this._cam_axisZ.z = 1.0;
  61394. // cases when the World Matrix is to be computed first
  61395. if (this.billboard || this._depthSort) {
  61396. this.mesh.computeWorldMatrix(true);
  61397. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  61398. }
  61399. // if the particles will always face the camera
  61400. if (this.billboard) {
  61401. // compute the camera position and un-rotate it by the current mesh rotation
  61402. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  61403. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  61404. this._cam_axisZ.normalize();
  61405. // same for camera up vector extracted from the cam view matrix
  61406. var view = this._camera.getViewMatrix(true);
  61407. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  61408. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  61409. this._cam_axisY.normalize();
  61410. this._cam_axisX.normalize();
  61411. }
  61412. // if depthSort, compute the camera global position in the mesh local system
  61413. if (this._depthSort) {
  61414. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  61415. }
  61416. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  61417. var idx = 0; // current position index in the global array positions32
  61418. var index = 0; // position start index in the global array positions32 of the current particle
  61419. var colidx = 0; // current color index in the global array colors32
  61420. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  61421. var uvidx = 0; // current uv index in the global array uvs32
  61422. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  61423. var pt = 0; // current index in the particle model shape
  61424. if (this.mesh.isFacetDataEnabled) {
  61425. this._computeBoundingBox = true;
  61426. }
  61427. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  61428. if (this._computeBoundingBox) {
  61429. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  61430. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  61431. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  61432. }
  61433. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  61434. if (this.mesh._boundingInfo) {
  61435. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  61436. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  61437. }
  61438. }
  61439. }
  61440. // particle loop
  61441. index = this.particles[start]._pos;
  61442. var vpos = (index / 3) | 0;
  61443. colorIndex = vpos * 4;
  61444. uvIndex = vpos * 2;
  61445. for (var p = start; p <= end; p++) {
  61446. this._particle = this.particles[p];
  61447. this._shape = this._particle._model._shape;
  61448. this._shapeUV = this._particle._model._shapeUV;
  61449. // call to custom user function to update the particle properties
  61450. this.updateParticle(this._particle);
  61451. // camera-particle distance for depth sorting
  61452. if (this._depthSort && this._depthSortParticles) {
  61453. var dsp = this.depthSortedParticles[p];
  61454. dsp.ind = this._particle._ind;
  61455. dsp.indicesLength = this._particle._model._indicesLength;
  61456. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  61457. }
  61458. // skip the computations for inactive or already invisible particles
  61459. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  61460. // increment indexes for the next particle
  61461. pt = this._shape.length;
  61462. index += pt * 3;
  61463. colorIndex += pt * 4;
  61464. uvIndex += pt * 2;
  61465. continue;
  61466. }
  61467. if (this._particle.isVisible) {
  61468. this._particle._stillInvisible = false; // un-mark permanent invisibility
  61469. this._particleHasParent = (this._particle.parentId !== null);
  61470. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  61471. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  61472. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  61473. // particle rotation matrix
  61474. if (this.billboard) {
  61475. this._particle.rotation.x = 0.0;
  61476. this._particle.rotation.y = 0.0;
  61477. }
  61478. if (this._computeParticleRotation || this.billboard) {
  61479. if (this._particle.rotationQuaternion) {
  61480. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  61481. }
  61482. else {
  61483. this._yaw = this._particle.rotation.y;
  61484. this._pitch = this._particle.rotation.x;
  61485. this._roll = this._particle.rotation.z;
  61486. this._quaternionRotationYPR();
  61487. }
  61488. this._quaternionToRotationMatrix();
  61489. }
  61490. if (this._particleHasParent) {
  61491. this._parent = this.particles[this._particle.parentId];
  61492. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  61493. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  61494. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  61495. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  61496. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  61497. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  61498. if (this._computeParticleRotation || this.billboard) {
  61499. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  61500. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  61501. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  61502. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  61503. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  61504. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  61505. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  61506. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  61507. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  61508. }
  61509. }
  61510. else {
  61511. this._particle._globalPosition.x = this._particle.position.x;
  61512. this._particle._globalPosition.y = this._particle.position.y;
  61513. this._particle._globalPosition.z = this._particle.position.z;
  61514. if (this._computeParticleRotation || this.billboard) {
  61515. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  61516. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  61517. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  61518. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  61519. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  61520. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  61521. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  61522. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  61523. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  61524. }
  61525. }
  61526. if (this._particle.translateFromPivot) {
  61527. this._pivotBackTranslation.x = 0.0;
  61528. this._pivotBackTranslation.y = 0.0;
  61529. this._pivotBackTranslation.z = 0.0;
  61530. }
  61531. else {
  61532. this._pivotBackTranslation.x = this._scaledPivot.x;
  61533. this._pivotBackTranslation.y = this._scaledPivot.y;
  61534. this._pivotBackTranslation.z = this._scaledPivot.z;
  61535. }
  61536. // particle vertex loop
  61537. for (pt = 0; pt < this._shape.length; pt++) {
  61538. idx = index + pt * 3;
  61539. colidx = colorIndex + pt * 4;
  61540. uvidx = uvIndex + pt * 2;
  61541. this._vertex.x = this._shape[pt].x;
  61542. this._vertex.y = this._shape[pt].y;
  61543. this._vertex.z = this._shape[pt].z;
  61544. if (this._computeParticleVertex) {
  61545. this.updateParticleVertex(this._particle, this._vertex, pt);
  61546. }
  61547. // positions
  61548. this._vertex.x *= this._particle.scaling.x;
  61549. this._vertex.y *= this._particle.scaling.y;
  61550. this._vertex.z *= this._particle.scaling.z;
  61551. this._vertex.x -= this._scaledPivot.x;
  61552. this._vertex.y -= this._scaledPivot.y;
  61553. this._vertex.z -= this._scaledPivot.z;
  61554. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61555. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61556. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61557. this._rotated.x += this._pivotBackTranslation.x;
  61558. this._rotated.y += this._pivotBackTranslation.y;
  61559. this._rotated.z += this._pivotBackTranslation.z;
  61560. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61561. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61562. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61563. if (this._computeBoundingBox) {
  61564. if (this._positions32[idx] < this._minimum.x) {
  61565. this._minimum.x = this._positions32[idx];
  61566. }
  61567. if (this._positions32[idx] > this._maximum.x) {
  61568. this._maximum.x = this._positions32[idx];
  61569. }
  61570. if (this._positions32[idx + 1] < this._minimum.y) {
  61571. this._minimum.y = this._positions32[idx + 1];
  61572. }
  61573. if (this._positions32[idx + 1] > this._maximum.y) {
  61574. this._maximum.y = this._positions32[idx + 1];
  61575. }
  61576. if (this._positions32[idx + 2] < this._minimum.z) {
  61577. this._minimum.z = this._positions32[idx + 2];
  61578. }
  61579. if (this._positions32[idx + 2] > this._maximum.z) {
  61580. this._maximum.z = this._positions32[idx + 2];
  61581. }
  61582. }
  61583. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  61584. if (!this._computeParticleVertex) {
  61585. this._normal.x = this._fixedNormal32[idx];
  61586. this._normal.y = this._fixedNormal32[idx + 1];
  61587. this._normal.z = this._fixedNormal32[idx + 2];
  61588. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  61589. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  61590. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  61591. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61592. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61593. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61594. }
  61595. if (this._computeParticleColor && this._particle.color) {
  61596. this._colors32[colidx] = this._particle.color.r;
  61597. this._colors32[colidx + 1] = this._particle.color.g;
  61598. this._colors32[colidx + 2] = this._particle.color.b;
  61599. this._colors32[colidx + 3] = this._particle.color.a;
  61600. }
  61601. if (this._computeParticleTexture) {
  61602. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61603. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61604. }
  61605. }
  61606. }
  61607. // particle just set invisible : scaled to zero and positioned at the origin
  61608. else {
  61609. this._particle._stillInvisible = true; // mark the particle as invisible
  61610. for (pt = 0; pt < this._shape.length; pt++) {
  61611. idx = index + pt * 3;
  61612. colidx = colorIndex + pt * 4;
  61613. uvidx = uvIndex + pt * 2;
  61614. this._positions32[idx] = 0.0;
  61615. this._positions32[idx + 1] = 0.0;
  61616. this._positions32[idx + 2] = 0.0;
  61617. this._normals32[idx] = 0.0;
  61618. this._normals32[idx + 1] = 0.0;
  61619. this._normals32[idx + 2] = 0.0;
  61620. if (this._computeParticleColor && this._particle.color) {
  61621. this._colors32[colidx] = this._particle.color.r;
  61622. this._colors32[colidx + 1] = this._particle.color.g;
  61623. this._colors32[colidx + 2] = this._particle.color.b;
  61624. this._colors32[colidx + 3] = this._particle.color.a;
  61625. }
  61626. if (this._computeParticleTexture) {
  61627. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  61628. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  61629. }
  61630. }
  61631. }
  61632. // if the particle intersections must be computed : update the bbInfo
  61633. if (this._particlesIntersect) {
  61634. var bInfo = this._particle._boundingInfo;
  61635. var bBox = bInfo.boundingBox;
  61636. var bSphere = bInfo.boundingSphere;
  61637. if (!this._bSphereOnly) {
  61638. // place, scale and rotate the particle bbox within the SPS local system, then update it
  61639. for (var b = 0; b < bBox.vectors.length; b++) {
  61640. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  61641. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  61642. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  61643. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  61644. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  61645. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  61646. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  61647. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  61648. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  61649. }
  61650. bBox._update(this.mesh._worldMatrix);
  61651. }
  61652. // place and scale the particle bouding sphere in the SPS local system, then update it
  61653. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  61654. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  61655. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  61656. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  61657. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  61658. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  61659. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  61660. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  61661. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  61662. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  61663. bSphere._update(this.mesh._worldMatrix);
  61664. }
  61665. // increment indexes for the next particle
  61666. index = idx + 3;
  61667. colorIndex = colidx + 4;
  61668. uvIndex = uvidx + 2;
  61669. }
  61670. // if the VBO must be updated
  61671. if (update) {
  61672. if (this._computeParticleColor) {
  61673. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  61674. }
  61675. if (this._computeParticleTexture) {
  61676. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  61677. }
  61678. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  61679. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  61680. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  61681. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  61682. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  61683. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  61684. for (var i = 0; i < this._normals32.length; i++) {
  61685. this._fixedNormal32[i] = this._normals32[i];
  61686. }
  61687. }
  61688. if (!this.mesh.areNormalsFrozen) {
  61689. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  61690. }
  61691. }
  61692. if (this._depthSort && this._depthSortParticles) {
  61693. this.depthSortedParticles.sort(this._depthSortFunction);
  61694. var dspl = this.depthSortedParticles.length;
  61695. var sorted = 0;
  61696. var lind = 0;
  61697. var sind = 0;
  61698. var sid = 0;
  61699. for (sorted = 0; sorted < dspl; sorted++) {
  61700. lind = this.depthSortedParticles[sorted].indicesLength;
  61701. sind = this.depthSortedParticles[sorted].ind;
  61702. for (var i = 0; i < lind; i++) {
  61703. this._indices32[sid] = this._indices[sind + i];
  61704. sid++;
  61705. }
  61706. }
  61707. this.mesh.updateIndices(this._indices32);
  61708. }
  61709. }
  61710. if (this._computeBoundingBox) {
  61711. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  61712. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  61713. }
  61714. this.afterUpdateParticles(start, end, update);
  61715. return this;
  61716. };
  61717. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  61718. this._halfroll = this._roll * 0.5;
  61719. this._halfpitch = this._pitch * 0.5;
  61720. this._halfyaw = this._yaw * 0.5;
  61721. this._sinRoll = Math.sin(this._halfroll);
  61722. this._cosRoll = Math.cos(this._halfroll);
  61723. this._sinPitch = Math.sin(this._halfpitch);
  61724. this._cosPitch = Math.cos(this._halfpitch);
  61725. this._sinYaw = Math.sin(this._halfyaw);
  61726. this._cosYaw = Math.cos(this._halfyaw);
  61727. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  61728. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  61729. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  61730. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  61731. };
  61732. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  61733. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  61734. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  61735. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  61736. this._rotMatrix.m[3] = 0;
  61737. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  61738. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  61739. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  61740. this._rotMatrix.m[7] = 0;
  61741. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  61742. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  61743. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  61744. this._rotMatrix.m[11] = 0;
  61745. this._rotMatrix.m[12] = 0;
  61746. this._rotMatrix.m[13] = 0;
  61747. this._rotMatrix.m[14] = 0;
  61748. this._rotMatrix.m[15] = 1.0;
  61749. };
  61750. /**
  61751. * Disposes the SPS.
  61752. */
  61753. SolidParticleSystem.prototype.dispose = function () {
  61754. this.mesh.dispose();
  61755. this.vars = null;
  61756. // drop references to internal big arrays for the GC
  61757. this._positions = null;
  61758. this._indices = null;
  61759. this._normals = null;
  61760. this._uvs = null;
  61761. this._colors = null;
  61762. this._indices32 = null;
  61763. this._positions32 = null;
  61764. this._normals32 = null;
  61765. this._fixedNormal32 = null;
  61766. this._uvs32 = null;
  61767. this._colors32 = null;
  61768. this.pickedParticles = null;
  61769. };
  61770. /**
  61771. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  61772. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61773. * @returns the SPS.
  61774. */
  61775. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  61776. if (!this._isVisibilityBoxLocked) {
  61777. this.mesh.refreshBoundingInfo();
  61778. }
  61779. return this;
  61780. };
  61781. /**
  61782. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  61783. * @param size the size (float) of the visibility box
  61784. * note : this doesn't lock the SPS mesh bounding box.
  61785. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61786. */
  61787. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  61788. var vis = size / 2;
  61789. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  61790. };
  61791. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  61792. /**
  61793. * Gets whether the SPS as always visible or not
  61794. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61795. */
  61796. get: function () {
  61797. return this._alwaysVisible;
  61798. },
  61799. /**
  61800. * Sets the SPS as always visible or not
  61801. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61802. */
  61803. set: function (val) {
  61804. this._alwaysVisible = val;
  61805. this.mesh.alwaysSelectAsActiveMesh = val;
  61806. },
  61807. enumerable: true,
  61808. configurable: true
  61809. });
  61810. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  61811. /**
  61812. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61814. */
  61815. get: function () {
  61816. return this._isVisibilityBoxLocked;
  61817. },
  61818. /**
  61819. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  61820. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  61821. */
  61822. set: function (val) {
  61823. this._isVisibilityBoxLocked = val;
  61824. var boundingInfo = this.mesh.getBoundingInfo();
  61825. boundingInfo.isLocked = val;
  61826. },
  61827. enumerable: true,
  61828. configurable: true
  61829. });
  61830. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  61831. /**
  61832. * Gets if `setParticles()` computes the particle rotations or not.
  61833. * Default value : true. The SPS is faster when it's set to false.
  61834. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61835. */
  61836. get: function () {
  61837. return this._computeParticleRotation;
  61838. },
  61839. /**
  61840. * Tells to `setParticles()` to compute the particle rotations or not.
  61841. * Default value : true. The SPS is faster when it's set to false.
  61842. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  61843. */
  61844. set: function (val) {
  61845. this._computeParticleRotation = val;
  61846. },
  61847. enumerable: true,
  61848. configurable: true
  61849. });
  61850. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  61851. /**
  61852. * Gets if `setParticles()` computes the particle colors or not.
  61853. * Default value : true. The SPS is faster when it's set to false.
  61854. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61855. */
  61856. get: function () {
  61857. return this._computeParticleColor;
  61858. },
  61859. /**
  61860. * Tells to `setParticles()` to compute the particle colors or not.
  61861. * Default value : true. The SPS is faster when it's set to false.
  61862. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  61863. */
  61864. set: function (val) {
  61865. this._computeParticleColor = val;
  61866. },
  61867. enumerable: true,
  61868. configurable: true
  61869. });
  61870. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  61871. /**
  61872. * Gets if `setParticles()` computes the particle textures or not.
  61873. * Default value : true. The SPS is faster when it's set to false.
  61874. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  61875. */
  61876. get: function () {
  61877. return this._computeParticleTexture;
  61878. },
  61879. set: function (val) {
  61880. this._computeParticleTexture = val;
  61881. },
  61882. enumerable: true,
  61883. configurable: true
  61884. });
  61885. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  61886. /**
  61887. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  61888. * Default value : false. The SPS is faster when it's set to false.
  61889. * Note : the particle custom vertex positions aren't stored values.
  61890. */
  61891. get: function () {
  61892. return this._computeParticleVertex;
  61893. },
  61894. /**
  61895. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  61896. * Default value : false. The SPS is faster when it's set to false.
  61897. * Note : the particle custom vertex positions aren't stored values.
  61898. */
  61899. set: function (val) {
  61900. this._computeParticleVertex = val;
  61901. },
  61902. enumerable: true,
  61903. configurable: true
  61904. });
  61905. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  61906. /**
  61907. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  61908. */
  61909. get: function () {
  61910. return this._computeBoundingBox;
  61911. },
  61912. /**
  61913. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  61914. */
  61915. set: function (val) {
  61916. this._computeBoundingBox = val;
  61917. },
  61918. enumerable: true,
  61919. configurable: true
  61920. });
  61921. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  61922. /**
  61923. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  61924. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61925. * Default : `true`
  61926. */
  61927. get: function () {
  61928. return this._depthSortParticles;
  61929. },
  61930. /**
  61931. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  61932. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  61933. * Default : `true`
  61934. */
  61935. set: function (val) {
  61936. this._depthSortParticles = val;
  61937. },
  61938. enumerable: true,
  61939. configurable: true
  61940. });
  61941. // =======================================================================
  61942. // Particle behavior logic
  61943. // these following methods may be overwritten by the user to fit his needs
  61944. /**
  61945. * This function does nothing. It may be overwritten to set all the particle first values.
  61946. * The SPS doesn't call this function, you may have to call it by your own.
  61947. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61948. */
  61949. SolidParticleSystem.prototype.initParticles = function () {
  61950. };
  61951. /**
  61952. * This function does nothing. It may be overwritten to recycle a particle.
  61953. * The SPS doesn't call this function, you may have to call it by your own.
  61954. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61955. * @param particle The particle to recycle
  61956. * @returns the recycled particle
  61957. */
  61958. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  61959. return particle;
  61960. };
  61961. /**
  61962. * Updates a particle : this function should be overwritten by the user.
  61963. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  61964. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  61965. * @example : just set a particle position or velocity and recycle conditions
  61966. * @param particle The particle to update
  61967. * @returns the updated particle
  61968. */
  61969. SolidParticleSystem.prototype.updateParticle = function (particle) {
  61970. return particle;
  61971. };
  61972. /**
  61973. * Updates a vertex of a particle : it can be overwritten by the user.
  61974. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  61975. * @param particle the current particle
  61976. * @param vertex the current index of the current particle
  61977. * @param pt the index of the current vertex in the particle shape
  61978. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  61979. * @example : just set a vertex particle position
  61980. * @returns the updated vertex
  61981. */
  61982. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  61983. return vertex;
  61984. };
  61985. /**
  61986. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  61987. * This does nothing and may be overwritten by the user.
  61988. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61989. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61990. * @param update the boolean update value actually passed to setParticles()
  61991. */
  61992. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  61993. };
  61994. /**
  61995. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  61996. * This will be passed three parameters.
  61997. * This does nothing and may be overwritten by the user.
  61998. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  61999. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62000. * @param update the boolean update value actually passed to setParticles()
  62001. */
  62002. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62003. };
  62004. return SolidParticleSystem;
  62005. }());
  62006. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62007. })(BABYLON || (BABYLON = {}));
  62008. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62009. var BABYLON;
  62010. (function (BABYLON) {
  62011. /**
  62012. * Class containing static functions to help procedurally build meshes
  62013. */
  62014. var MeshBuilder = /** @class */ (function () {
  62015. function MeshBuilder() {
  62016. }
  62017. MeshBuilder.updateSideOrientation = function (orientation) {
  62018. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62019. return BABYLON.Mesh.DOUBLESIDE;
  62020. }
  62021. if (orientation === undefined || orientation === null) {
  62022. return BABYLON.Mesh.FRONTSIDE;
  62023. }
  62024. return orientation;
  62025. };
  62026. /**
  62027. * Creates a box mesh
  62028. * * The parameter `size` sets the size (float) of each box side (default 1)
  62029. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  62030. * * 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)
  62031. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62032. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62033. * * 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
  62034. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62035. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  62036. * @param name defines the name of the mesh
  62037. * @param options defines the options used to create the mesh
  62038. * @param scene defines the hosting scene
  62039. * @returns the box mesh
  62040. */
  62041. MeshBuilder.CreateBox = function (name, options, scene) {
  62042. if (scene === void 0) { scene = null; }
  62043. var box = new BABYLON.Mesh(name, scene);
  62044. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62045. box._originalBuilderSideOrientation = options.sideOrientation;
  62046. var vertexData = BABYLON.VertexData.CreateBox(options);
  62047. vertexData.applyToMesh(box, options.updatable);
  62048. return box;
  62049. };
  62050. /**
  62051. * Creates a sphere mesh
  62052. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  62053. * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`)
  62054. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  62055. * * 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
  62056. * * 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)
  62057. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62058. * * 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
  62059. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62060. * @param name defines the name of the mesh
  62061. * @param options defines the options used to create the mesh
  62062. * @param scene defines the hosting scene
  62063. * @returns the sphere mesh
  62064. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  62065. */
  62066. MeshBuilder.CreateSphere = function (name, options, scene) {
  62067. var sphere = new BABYLON.Mesh(name, scene);
  62068. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62069. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62070. var vertexData = BABYLON.VertexData.CreateSphere(options);
  62071. vertexData.applyToMesh(sphere, options.updatable);
  62072. return sphere;
  62073. };
  62074. /**
  62075. * Creates a plane polygonal mesh. By default, this is a disc
  62076. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  62077. * * 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
  62078. * * 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
  62079. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62080. * * 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
  62081. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62082. * @param name defines the name of the mesh
  62083. * @param options defines the options used to create the mesh
  62084. * @param scene defines the hosting scene
  62085. * @returns the plane polygonal mesh
  62086. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  62087. */
  62088. MeshBuilder.CreateDisc = function (name, options, scene) {
  62089. if (scene === void 0) { scene = null; }
  62090. var disc = new BABYLON.Mesh(name, scene);
  62091. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62092. disc._originalBuilderSideOrientation = options.sideOrientation;
  62093. var vertexData = BABYLON.VertexData.CreateDisc(options);
  62094. vertexData.applyToMesh(disc, options.updatable);
  62095. return disc;
  62096. };
  62097. /**
  62098. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  62099. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  62100. * * 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`)
  62101. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  62102. * * 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
  62103. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62104. * * 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
  62105. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62106. * @param name defines the name of the mesh
  62107. * @param options defines the options used to create the mesh
  62108. * @param scene defines the hosting scene
  62109. * @returns the icosahedron mesh
  62110. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  62111. */
  62112. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  62113. var sphere = new BABYLON.Mesh(name, scene);
  62114. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62115. sphere._originalBuilderSideOrientation = options.sideOrientation;
  62116. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  62117. vertexData.applyToMesh(sphere, options.updatable);
  62118. return sphere;
  62119. };
  62120. ;
  62121. /**
  62122. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62123. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  62124. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  62125. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  62126. * * 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
  62127. * * 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
  62128. * * 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
  62129. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62130. * * 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
  62131. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62132. * * 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
  62133. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  62134. * * 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
  62135. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  62136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62137. * @param name defines the name of the mesh
  62138. * @param options defines the options used to create the mesh
  62139. * @param scene defines the hosting scene
  62140. * @returns the ribbon mesh
  62141. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  62142. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62143. */
  62144. MeshBuilder.CreateRibbon = function (name, options, scene) {
  62145. if (scene === void 0) { scene = null; }
  62146. var pathArray = options.pathArray;
  62147. var closeArray = options.closeArray;
  62148. var closePath = options.closePath;
  62149. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62150. var instance = options.instance;
  62151. var updatable = options.updatable;
  62152. if (instance) { // existing ribbon instance update
  62153. // positionFunction : ribbon case
  62154. // only pathArray and sideOrientation parameters are taken into account for positions update
  62155. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  62156. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  62157. var positionFunction = function (positions) {
  62158. var minlg = pathArray[0].length;
  62159. var i = 0;
  62160. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  62161. for (var si = 1; si <= ns; si++) {
  62162. for (var p = 0; p < pathArray.length; p++) {
  62163. var path = pathArray[p];
  62164. var l = path.length;
  62165. minlg = (minlg < l) ? minlg : l;
  62166. var j = 0;
  62167. while (j < minlg) {
  62168. positions[i] = path[j].x;
  62169. positions[i + 1] = path[j].y;
  62170. positions[i + 2] = path[j].z;
  62171. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  62172. BABYLON.Tmp.Vector3[0].x = path[j].x;
  62173. }
  62174. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  62175. BABYLON.Tmp.Vector3[1].x = path[j].x;
  62176. }
  62177. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  62178. BABYLON.Tmp.Vector3[0].y = path[j].y;
  62179. }
  62180. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  62181. BABYLON.Tmp.Vector3[1].y = path[j].y;
  62182. }
  62183. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  62184. BABYLON.Tmp.Vector3[0].z = path[j].z;
  62185. }
  62186. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  62187. BABYLON.Tmp.Vector3[1].z = path[j].z;
  62188. }
  62189. j++;
  62190. i += 3;
  62191. }
  62192. if (instance._closePath) {
  62193. positions[i] = path[0].x;
  62194. positions[i + 1] = path[0].y;
  62195. positions[i + 2] = path[0].z;
  62196. i += 3;
  62197. }
  62198. }
  62199. }
  62200. };
  62201. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62202. positionFunction(positions);
  62203. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  62204. instance._boundingInfo.update(instance._worldMatrix);
  62205. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62206. if (options.colors) {
  62207. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62208. for (var c = 0; c < options.colors.length; c++) {
  62209. colors[c * 4] = options.colors[c].r;
  62210. colors[c * 4 + 1] = options.colors[c].g;
  62211. colors[c * 4 + 2] = options.colors[c].b;
  62212. colors[c * 4 + 3] = options.colors[c].a;
  62213. }
  62214. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  62215. }
  62216. if (options.uvs) {
  62217. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62218. for (var i = 0; i < options.uvs.length; i++) {
  62219. uvs[i * 2] = options.uvs[i].x;
  62220. uvs[i * 2 + 1] = options.uvs[i].y;
  62221. }
  62222. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  62223. }
  62224. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  62225. var indices = instance.getIndices();
  62226. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62227. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  62228. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  62229. if (instance._closePath) {
  62230. var indexFirst = 0;
  62231. var indexLast = 0;
  62232. for (var p = 0; p < pathArray.length; p++) {
  62233. indexFirst = instance._idx[p] * 3;
  62234. if (p + 1 < pathArray.length) {
  62235. indexLast = (instance._idx[p + 1] - 1) * 3;
  62236. }
  62237. else {
  62238. indexLast = normals.length - 3;
  62239. }
  62240. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  62241. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  62242. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  62243. normals[indexLast] = normals[indexFirst];
  62244. normals[indexLast + 1] = normals[indexFirst + 1];
  62245. normals[indexLast + 2] = normals[indexFirst + 2];
  62246. }
  62247. }
  62248. if (!(instance.areNormalsFrozen)) {
  62249. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  62250. }
  62251. }
  62252. return instance;
  62253. }
  62254. else { // new ribbon creation
  62255. var ribbon = new BABYLON.Mesh(name, scene);
  62256. ribbon._originalBuilderSideOrientation = sideOrientation;
  62257. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  62258. if (closePath) {
  62259. ribbon._idx = vertexData._idx;
  62260. }
  62261. ribbon._closePath = closePath;
  62262. ribbon._closeArray = closeArray;
  62263. vertexData.applyToMesh(ribbon, updatable);
  62264. return ribbon;
  62265. }
  62266. };
  62267. /**
  62268. * Creates a cylinder or a cone mesh
  62269. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  62270. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  62271. * * 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.
  62272. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  62273. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  62274. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  62275. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  62276. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  62277. * * 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).
  62278. * * 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
  62279. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  62280. * * 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
  62281. * * 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.
  62282. * * If `enclose` is false, a ring surface is one element.
  62283. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  62284. * * 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
  62285. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62286. * * 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
  62287. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62288. * @param name defines the name of the mesh
  62289. * @param options defines the options used to create the mesh
  62290. * @param scene defines the hosting scene
  62291. * @returns the cylinder mesh
  62292. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  62293. */
  62294. MeshBuilder.CreateCylinder = function (name, options, scene) {
  62295. var cylinder = new BABYLON.Mesh(name, scene);
  62296. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62297. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  62298. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  62299. vertexData.applyToMesh(cylinder, options.updatable);
  62300. return cylinder;
  62301. };
  62302. /**
  62303. * Creates a torus mesh
  62304. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  62305. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  62306. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  62307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62308. * * 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
  62309. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62310. * @param name defines the name of the mesh
  62311. * @param options defines the options used to create the mesh
  62312. * @param scene defines the hosting scene
  62313. * @returns the torus mesh
  62314. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  62315. */
  62316. MeshBuilder.CreateTorus = function (name, options, scene) {
  62317. var torus = new BABYLON.Mesh(name, scene);
  62318. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62319. torus._originalBuilderSideOrientation = options.sideOrientation;
  62320. var vertexData = BABYLON.VertexData.CreateTorus(options);
  62321. vertexData.applyToMesh(torus, options.updatable);
  62322. return torus;
  62323. };
  62324. /**
  62325. * Creates a torus knot mesh
  62326. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  62327. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  62328. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  62329. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  62330. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62331. * * 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
  62332. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62333. * @param name defines the name of the mesh
  62334. * @param options defines the options used to create the mesh
  62335. * @param scene defines the hosting scene
  62336. * @returns the torus knot mesh
  62337. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  62338. */
  62339. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  62340. var torusKnot = new BABYLON.Mesh(name, scene);
  62341. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62342. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  62343. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  62344. vertexData.applyToMesh(torusKnot, options.updatable);
  62345. return torusKnot;
  62346. };
  62347. /**
  62348. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  62349. * * 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
  62350. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  62351. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  62352. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  62353. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  62354. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  62355. * * 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
  62356. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  62357. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62358. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  62359. * @param name defines the name of the new line system
  62360. * @param options defines the options used to create the line system
  62361. * @param scene defines the hosting scene
  62362. * @returns a new line system mesh
  62363. */
  62364. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  62365. var instance = options.instance;
  62366. var lines = options.lines;
  62367. var colors = options.colors;
  62368. if (instance) { // lines update
  62369. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62370. var vertexColor;
  62371. var lineColors;
  62372. if (colors) {
  62373. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62374. }
  62375. var i = 0;
  62376. var c = 0;
  62377. for (var l = 0; l < lines.length; l++) {
  62378. var points = lines[l];
  62379. for (var p = 0; p < points.length; p++) {
  62380. positions[i] = points[p].x;
  62381. positions[i + 1] = points[p].y;
  62382. positions[i + 2] = points[p].z;
  62383. if (colors && vertexColor) {
  62384. lineColors = colors[l];
  62385. vertexColor[c] = lineColors[p].r;
  62386. vertexColor[c + 1] = lineColors[p].g;
  62387. vertexColor[c + 2] = lineColors[p].b;
  62388. vertexColor[c + 3] = lineColors[p].a;
  62389. c += 4;
  62390. }
  62391. i += 3;
  62392. }
  62393. }
  62394. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  62395. if (colors && vertexColor) {
  62396. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  62397. }
  62398. return instance;
  62399. }
  62400. // line system creation
  62401. var useVertexColor = (colors) ? true : false;
  62402. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  62403. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  62404. vertexData.applyToMesh(lineSystem, options.updatable);
  62405. return lineSystem;
  62406. };
  62407. /**
  62408. * Creates a line mesh
  62409. * 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
  62410. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62411. * * The parameter `points` is an array successive Vector3
  62412. * * 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
  62413. * * The optional parameter `colors` is an array of successive Color4, one per line point
  62414. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  62415. * * When updating an instance, remember that only point positions can change, not the number of points
  62416. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62417. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  62418. * @param name defines the name of the new line system
  62419. * @param options defines the options used to create the line system
  62420. * @param scene defines the hosting scene
  62421. * @returns a new line mesh
  62422. */
  62423. MeshBuilder.CreateLines = function (name, options, scene) {
  62424. if (scene === void 0) { scene = null; }
  62425. var colors = (options.colors) ? [options.colors] : null;
  62426. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  62427. return lines;
  62428. };
  62429. /**
  62430. * Creates a dashed line mesh
  62431. * * 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
  62432. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  62433. * * The parameter `points` is an array successive Vector3
  62434. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  62435. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  62436. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  62437. * * 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
  62438. * * When updating an instance, remember that only point positions can change, not the number of points
  62439. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62440. * @param name defines the name of the mesh
  62441. * @param options defines the options used to create the mesh
  62442. * @param scene defines the hosting scene
  62443. * @returns the dashed line mesh
  62444. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  62445. */
  62446. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  62447. if (scene === void 0) { scene = null; }
  62448. var points = options.points;
  62449. var instance = options.instance;
  62450. var gapSize = options.gapSize || 1;
  62451. var dashSize = options.dashSize || 3;
  62452. if (instance) { // dashed lines update
  62453. var positionFunction = function (positions) {
  62454. var curvect = BABYLON.Vector3.Zero();
  62455. var nbSeg = positions.length / 6;
  62456. var lg = 0;
  62457. var nb = 0;
  62458. var shft = 0;
  62459. var dashshft = 0;
  62460. var curshft = 0;
  62461. var p = 0;
  62462. var i = 0;
  62463. var j = 0;
  62464. for (i = 0; i < points.length - 1; i++) {
  62465. points[i + 1].subtractToRef(points[i], curvect);
  62466. lg += curvect.length();
  62467. }
  62468. shft = lg / nbSeg;
  62469. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  62470. for (i = 0; i < points.length - 1; i++) {
  62471. points[i + 1].subtractToRef(points[i], curvect);
  62472. nb = Math.floor(curvect.length() / shft);
  62473. curvect.normalize();
  62474. j = 0;
  62475. while (j < nb && p < positions.length) {
  62476. curshft = shft * j;
  62477. positions[p] = points[i].x + curshft * curvect.x;
  62478. positions[p + 1] = points[i].y + curshft * curvect.y;
  62479. positions[p + 2] = points[i].z + curshft * curvect.z;
  62480. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  62481. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  62482. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  62483. p += 6;
  62484. j++;
  62485. }
  62486. }
  62487. while (p < positions.length) {
  62488. positions[p] = points[i].x;
  62489. positions[p + 1] = points[i].y;
  62490. positions[p + 2] = points[i].z;
  62491. p += 3;
  62492. }
  62493. };
  62494. instance.updateMeshPositions(positionFunction, false);
  62495. return instance;
  62496. }
  62497. // dashed lines creation
  62498. var dashedLines = new BABYLON.LinesMesh(name, scene);
  62499. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  62500. vertexData.applyToMesh(dashedLines, options.updatable);
  62501. dashedLines.dashSize = dashSize;
  62502. dashedLines.gapSize = gapSize;
  62503. return dashedLines;
  62504. };
  62505. /**
  62506. * 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.
  62507. * * 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.
  62508. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62509. * * 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.
  62510. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  62511. * * 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
  62512. * * 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
  62513. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  62514. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62515. * * 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
  62516. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  62517. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62518. * @param name defines the name of the mesh
  62519. * @param options defines the options used to create the mesh
  62520. * @param scene defines the hosting scene
  62521. * @returns the extruded shape mesh
  62522. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62523. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62524. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62525. */
  62526. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  62527. if (scene === void 0) { scene = null; }
  62528. var path = options.path;
  62529. var shape = options.shape;
  62530. var scale = options.scale || 1;
  62531. var rotation = options.rotation || 0;
  62532. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62533. var updatable = options.updatable;
  62534. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62535. var instance = options.instance || null;
  62536. var invertUV = options.invertUV || false;
  62537. 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);
  62538. };
  62539. /**
  62540. * Creates an custom extruded shape mesh.
  62541. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  62542. * * 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.
  62543. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  62544. * * 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
  62545. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  62546. * * 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
  62547. * * It must returns a float value that will be the scale value applied to the shape on each path point
  62548. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  62549. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  62550. * * 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
  62551. * * 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
  62552. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  62553. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62554. * * 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
  62555. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62556. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62557. * @param name defines the name of the mesh
  62558. * @param options defines the options used to create the mesh
  62559. * @param scene defines the hosting scene
  62560. * @returns the custom extruded shape mesh
  62561. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  62562. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62563. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  62564. */
  62565. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  62566. var path = options.path;
  62567. var shape = options.shape;
  62568. var scaleFunction = options.scaleFunction || (function () { return 1; });
  62569. var rotationFunction = options.rotationFunction || (function () { return 0; });
  62570. var ribbonCloseArray = options.ribbonCloseArray || false;
  62571. var ribbonClosePath = options.ribbonClosePath || false;
  62572. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  62573. var updatable = options.updatable;
  62574. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62575. var instance = options.instance;
  62576. var invertUV = options.invertUV || false;
  62577. 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);
  62578. };
  62579. /**
  62580. * Creates lathe mesh.
  62581. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  62582. * * 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
  62583. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  62584. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  62585. * * 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
  62586. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  62587. * * 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
  62588. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62589. * * 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
  62590. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62591. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62592. * @param name defines the name of the mesh
  62593. * @param options defines the options used to create the mesh
  62594. * @param scene defines the hosting scene
  62595. * @returns the lathe mesh
  62596. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  62597. */
  62598. MeshBuilder.CreateLathe = function (name, options, scene) {
  62599. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  62600. var closed = (options.closed === undefined) ? true : options.closed;
  62601. var shape = options.shape;
  62602. var radius = options.radius || 1;
  62603. var tessellation = options.tessellation || 64;
  62604. var updatable = options.updatable;
  62605. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62606. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62607. var pi2 = Math.PI * 2;
  62608. var paths = new Array();
  62609. var invertUV = options.invertUV || false;
  62610. var i = 0;
  62611. var p = 0;
  62612. var step = pi2 / tessellation * arc;
  62613. var rotated;
  62614. var path = new Array();
  62615. for (i = 0; i <= tessellation; i++) {
  62616. var path = [];
  62617. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  62618. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  62619. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  62620. }
  62621. for (p = 0; p < shape.length; p++) {
  62622. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  62623. path.push(rotated);
  62624. }
  62625. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  62626. 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));
  62627. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  62628. }
  62629. paths.push(path);
  62630. }
  62631. // lathe ribbon
  62632. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62633. return lathe;
  62634. };
  62635. /**
  62636. * Creates a plane mesh
  62637. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  62638. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  62639. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  62640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62641. * * 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
  62642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62643. * @param name defines the name of the mesh
  62644. * @param options defines the options used to create the mesh
  62645. * @param scene defines the hosting scene
  62646. * @returns the plane mesh
  62647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62648. */
  62649. MeshBuilder.CreatePlane = function (name, options, scene) {
  62650. var plane = new BABYLON.Mesh(name, scene);
  62651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62652. plane._originalBuilderSideOrientation = options.sideOrientation;
  62653. var vertexData = BABYLON.VertexData.CreatePlane(options);
  62654. vertexData.applyToMesh(plane, options.updatable);
  62655. if (options.sourcePlane) {
  62656. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  62657. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  62658. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  62659. plane.rotate(vectorProduct, product);
  62660. }
  62661. return plane;
  62662. };
  62663. /**
  62664. * Creates a ground mesh
  62665. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  62666. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  62667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62668. * @param name defines the name of the mesh
  62669. * @param options defines the options used to create the mesh
  62670. * @param scene defines the hosting scene
  62671. * @returns the ground mesh
  62672. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  62673. */
  62674. MeshBuilder.CreateGround = function (name, options, scene) {
  62675. var ground = new BABYLON.GroundMesh(name, scene);
  62676. ground._setReady(false);
  62677. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  62678. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  62679. ground._width = options.width || 1;
  62680. ground._height = options.height || 1;
  62681. ground._maxX = ground._width / 2;
  62682. ground._maxZ = ground._height / 2;
  62683. ground._minX = -ground._maxX;
  62684. ground._minZ = -ground._maxZ;
  62685. var vertexData = BABYLON.VertexData.CreateGround(options);
  62686. vertexData.applyToMesh(ground, options.updatable);
  62687. ground._setReady(true);
  62688. return ground;
  62689. };
  62690. /**
  62691. * Creates a tiled ground mesh
  62692. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  62693. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  62694. * * 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
  62695. * * 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
  62696. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62697. * @param name defines the name of the mesh
  62698. * @param options defines the options used to create the mesh
  62699. * @param scene defines the hosting scene
  62700. * @returns the tiled ground mesh
  62701. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  62702. */
  62703. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  62704. var tiledGround = new BABYLON.Mesh(name, scene);
  62705. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  62706. vertexData.applyToMesh(tiledGround, options.updatable);
  62707. return tiledGround;
  62708. };
  62709. /**
  62710. * Creates a ground mesh from a height map
  62711. * * The parameter `url` sets the URL of the height map image resource.
  62712. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  62713. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  62714. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  62715. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  62716. * * 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.
  62717. * * 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).
  62718. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  62719. * @param name defines the name of the mesh
  62720. * @param url defines the url to the height map
  62721. * @param options defines the options used to create the mesh
  62722. * @param scene defines the hosting scene
  62723. * @returns the ground mesh
  62724. * @see http://doc.babylonjs.com/babylon101/height_map
  62725. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  62726. */
  62727. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  62728. var width = options.width || 10.0;
  62729. var height = options.height || 10.0;
  62730. var subdivisions = options.subdivisions || 1 | 0;
  62731. var minHeight = options.minHeight || 0.0;
  62732. var maxHeight = options.maxHeight || 1.0;
  62733. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  62734. var updatable = options.updatable;
  62735. var onReady = options.onReady;
  62736. var ground = new BABYLON.GroundMesh(name, scene);
  62737. ground._subdivisionsX = subdivisions;
  62738. ground._subdivisionsY = subdivisions;
  62739. ground._width = width;
  62740. ground._height = height;
  62741. ground._maxX = ground._width / 2.0;
  62742. ground._maxZ = ground._height / 2.0;
  62743. ground._minX = -ground._maxX;
  62744. ground._minZ = -ground._maxZ;
  62745. ground._setReady(false);
  62746. var onload = function (img) {
  62747. // Getting height map data
  62748. var canvas = document.createElement("canvas");
  62749. var context = canvas.getContext("2d");
  62750. if (!context) {
  62751. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  62752. }
  62753. if (scene.isDisposed) {
  62754. return;
  62755. }
  62756. var bufferWidth = img.width;
  62757. var bufferHeight = img.height;
  62758. canvas.width = bufferWidth;
  62759. canvas.height = bufferHeight;
  62760. context.drawImage(img, 0, 0);
  62761. // Create VertexData from map data
  62762. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  62763. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  62764. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  62765. width: width, height: height,
  62766. subdivisions: subdivisions,
  62767. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  62768. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  62769. });
  62770. vertexData.applyToMesh(ground, updatable);
  62771. //execute ready callback, if set
  62772. if (onReady) {
  62773. onReady(ground);
  62774. }
  62775. ground._setReady(true);
  62776. };
  62777. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  62778. return ground;
  62779. };
  62780. /**
  62781. * Creates a polygon mesh
  62782. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  62783. * * 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
  62784. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62785. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62786. * * 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)
  62787. * * Remember you can only change the shape positions, not their number when updating a polygon
  62788. * @param name defines the name of the mesh
  62789. * @param options defines the options used to create the mesh
  62790. * @param scene defines the hosting scene
  62791. * @returns the polygon mesh
  62792. */
  62793. MeshBuilder.CreatePolygon = function (name, options, scene) {
  62794. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62795. var shape = options.shape;
  62796. var holes = options.holes || [];
  62797. var depth = options.depth || 0;
  62798. var contours = [];
  62799. var hole = [];
  62800. for (var i = 0; i < shape.length; i++) {
  62801. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  62802. }
  62803. var epsilon = 0.00000001;
  62804. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  62805. contours.pop();
  62806. }
  62807. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  62808. for (var hNb = 0; hNb < holes.length; hNb++) {
  62809. hole = [];
  62810. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  62811. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  62812. }
  62813. polygonTriangulation.addHole(hole);
  62814. }
  62815. var polygon = polygonTriangulation.build(options.updatable, depth);
  62816. polygon._originalBuilderSideOrientation = options.sideOrientation;
  62817. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  62818. vertexData.applyToMesh(polygon, options.updatable);
  62819. return polygon;
  62820. };
  62821. ;
  62822. /**
  62823. * Creates an extruded polygon mesh, with depth in the Y direction.
  62824. * * 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)
  62825. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  62826. * @param name defines the name of the mesh
  62827. * @param options defines the options used to create the mesh
  62828. * @param scene defines the hosting scene
  62829. * @returns the polygon mesh
  62830. */
  62831. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  62832. return MeshBuilder.CreatePolygon(name, options, scene);
  62833. };
  62834. ;
  62835. /**
  62836. * Creates a tube mesh.
  62837. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  62838. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  62839. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  62840. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  62841. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  62842. * * 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)
  62843. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  62844. * * 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
  62845. * * 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
  62846. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62847. * * 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
  62848. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  62849. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62850. * @param name defines the name of the mesh
  62851. * @param options defines the options used to create the mesh
  62852. * @param scene defines the hosting scene
  62853. * @returns the tube mesh
  62854. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  62855. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  62856. */
  62857. MeshBuilder.CreateTube = function (name, options, scene) {
  62858. var path = options.path;
  62859. var instance = options.instance;
  62860. var radius = 1.0;
  62861. if (instance) {
  62862. radius = instance.radius;
  62863. }
  62864. if (options.radius !== undefined) {
  62865. radius = options.radius;
  62866. }
  62867. ;
  62868. var tessellation = options.tessellation || 64 | 0;
  62869. var radiusFunction = options.radiusFunction || null;
  62870. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  62871. var invertUV = options.invertUV || false;
  62872. var updatable = options.updatable;
  62873. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62874. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  62875. // tube geometry
  62876. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  62877. var tangents = path3D.getTangents();
  62878. var normals = path3D.getNormals();
  62879. var distances = path3D.getDistances();
  62880. var pi2 = Math.PI * 2;
  62881. var step = pi2 / tessellation * arc;
  62882. var returnRadius = function () { return radius; };
  62883. var radiusFunctionFinal = radiusFunction || returnRadius;
  62884. var circlePath;
  62885. var rad;
  62886. var normal;
  62887. var rotated;
  62888. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62889. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62890. for (var i = 0; i < path.length; i++) {
  62891. rad = radiusFunctionFinal(i, distances[i]); // current radius
  62892. circlePath = Array(); // current circle array
  62893. normal = normals[i]; // current normal
  62894. for (var t = 0; t < tessellation; t++) {
  62895. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  62896. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  62897. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  62898. rotated.scaleInPlace(rad).addInPlace(path[i]);
  62899. circlePath[t] = rotated;
  62900. }
  62901. circlePaths[index] = circlePath;
  62902. index++;
  62903. }
  62904. // cap
  62905. var capPath = function (nbPoints, pathIndex) {
  62906. var pointCap = Array();
  62907. for (var i = 0; i < nbPoints; i++) {
  62908. pointCap.push(path[pathIndex]);
  62909. }
  62910. return pointCap;
  62911. };
  62912. switch (cap) {
  62913. case BABYLON.Mesh.NO_CAP:
  62914. break;
  62915. case BABYLON.Mesh.CAP_START:
  62916. circlePaths[0] = capPath(tessellation, 0);
  62917. circlePaths[1] = circlePaths[2].slice(0);
  62918. break;
  62919. case BABYLON.Mesh.CAP_END:
  62920. circlePaths[index] = circlePaths[index - 1].slice(0);
  62921. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62922. break;
  62923. case BABYLON.Mesh.CAP_ALL:
  62924. circlePaths[0] = capPath(tessellation, 0);
  62925. circlePaths[1] = circlePaths[2].slice(0);
  62926. circlePaths[index] = circlePaths[index - 1].slice(0);
  62927. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  62928. break;
  62929. default:
  62930. break;
  62931. }
  62932. return circlePaths;
  62933. };
  62934. var path3D;
  62935. var pathArray;
  62936. if (instance) { // tube update
  62937. var arc = options.arc || instance.arc;
  62938. path3D = (instance.path3D).update(path);
  62939. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  62940. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  62941. instance.path3D = path3D;
  62942. instance.pathArray = pathArray;
  62943. instance.arc = arc;
  62944. instance.radius = radius;
  62945. return instance;
  62946. }
  62947. // tube creation
  62948. path3D = new BABYLON.Path3D(path);
  62949. var newPathArray = new Array();
  62950. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62951. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  62952. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  62953. tube.pathArray = pathArray;
  62954. tube.path3D = path3D;
  62955. tube.tessellation = tessellation;
  62956. tube.cap = cap;
  62957. tube.arc = options.arc;
  62958. tube.radius = radius;
  62959. return tube;
  62960. };
  62961. /**
  62962. * Creates a polyhedron mesh
  62963. * * 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
  62964. * * The parameter `size` (positive float, default 1) sets the polygon size
  62965. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  62966. * * 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`
  62967. * * 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
  62968. * * 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)`)
  62969. * * 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
  62970. * * 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
  62971. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  62972. * * 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
  62973. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  62974. * @param name defines the name of the mesh
  62975. * @param options defines the options used to create the mesh
  62976. * @param scene defines the hosting scene
  62977. * @returns the polyhedron mesh
  62978. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  62979. */
  62980. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  62981. var polyhedron = new BABYLON.Mesh(name, scene);
  62982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  62983. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  62984. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  62985. vertexData.applyToMesh(polyhedron, options.updatable);
  62986. return polyhedron;
  62987. };
  62988. /**
  62989. * Creates a decal mesh.
  62990. * 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
  62991. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  62992. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  62993. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  62994. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  62995. * @param name defines the name of the mesh
  62996. * @param sourceMesh defines the mesh where the decal must be applied
  62997. * @param options defines the options used to create the mesh
  62998. * @param scene defines the hosting scene
  62999. * @returns the decal mesh
  63000. * @see http://doc.babylonjs.com/how_to/decals
  63001. */
  63002. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63003. var indices = sourceMesh.getIndices();
  63004. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63005. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63006. var position = options.position || BABYLON.Vector3.Zero();
  63007. var normal = options.normal || BABYLON.Vector3.Up();
  63008. var size = options.size || BABYLON.Vector3.One();
  63009. var angle = options.angle || 0;
  63010. // Getting correct rotation
  63011. if (!normal) {
  63012. var target = new BABYLON.Vector3(0, 0, 1);
  63013. var camera = sourceMesh.getScene().activeCamera;
  63014. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63015. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63016. }
  63017. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63018. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63019. var pitch = Math.atan2(normal.y, len);
  63020. // Matrix
  63021. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63022. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63023. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63024. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  63025. var vertexData = new BABYLON.VertexData();
  63026. vertexData.indices = [];
  63027. vertexData.positions = [];
  63028. vertexData.normals = [];
  63029. vertexData.uvs = [];
  63030. var currentVertexDataIndex = 0;
  63031. var extractDecalVector3 = function (indexId) {
  63032. var result = new BABYLON.PositionNormalVertex();
  63033. if (!indices || !positions || !normals) {
  63034. return result;
  63035. }
  63036. var vertexId = indices[indexId];
  63037. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  63038. // Send vector to decal local world
  63039. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  63040. // Get normal
  63041. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  63042. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  63043. return result;
  63044. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  63045. var clip = function (vertices, axis) {
  63046. if (vertices.length === 0) {
  63047. return vertices;
  63048. }
  63049. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  63050. var clipVertices = function (v0, v1) {
  63051. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  63052. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  63053. };
  63054. var result = new Array();
  63055. for (var index = 0; index < vertices.length; index += 3) {
  63056. var v1Out;
  63057. var v2Out;
  63058. var v3Out;
  63059. var total = 0;
  63060. var nV1 = null;
  63061. var nV2 = null;
  63062. var nV3 = null;
  63063. var nV4 = null;
  63064. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  63065. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  63066. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  63067. v1Out = d1 > 0;
  63068. v2Out = d2 > 0;
  63069. v3Out = d3 > 0;
  63070. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  63071. switch (total) {
  63072. case 0:
  63073. result.push(vertices[index]);
  63074. result.push(vertices[index + 1]);
  63075. result.push(vertices[index + 2]);
  63076. break;
  63077. case 1:
  63078. if (v1Out) {
  63079. nV1 = vertices[index + 1];
  63080. nV2 = vertices[index + 2];
  63081. nV3 = clipVertices(vertices[index], nV1);
  63082. nV4 = clipVertices(vertices[index], nV2);
  63083. }
  63084. if (v2Out) {
  63085. nV1 = vertices[index];
  63086. nV2 = vertices[index + 2];
  63087. nV3 = clipVertices(vertices[index + 1], nV1);
  63088. nV4 = clipVertices(vertices[index + 1], nV2);
  63089. result.push(nV3);
  63090. result.push(nV2.clone());
  63091. result.push(nV1.clone());
  63092. result.push(nV2.clone());
  63093. result.push(nV3.clone());
  63094. result.push(nV4);
  63095. break;
  63096. }
  63097. if (v3Out) {
  63098. nV1 = vertices[index];
  63099. nV2 = vertices[index + 1];
  63100. nV3 = clipVertices(vertices[index + 2], nV1);
  63101. nV4 = clipVertices(vertices[index + 2], nV2);
  63102. }
  63103. if (nV1 && nV2 && nV3 && nV4) {
  63104. result.push(nV1.clone());
  63105. result.push(nV2.clone());
  63106. result.push(nV3);
  63107. result.push(nV4);
  63108. result.push(nV3.clone());
  63109. result.push(nV2.clone());
  63110. }
  63111. break;
  63112. case 2:
  63113. if (!v1Out) {
  63114. nV1 = vertices[index].clone();
  63115. nV2 = clipVertices(nV1, vertices[index + 1]);
  63116. nV3 = clipVertices(nV1, vertices[index + 2]);
  63117. result.push(nV1);
  63118. result.push(nV2);
  63119. result.push(nV3);
  63120. }
  63121. if (!v2Out) {
  63122. nV1 = vertices[index + 1].clone();
  63123. nV2 = clipVertices(nV1, vertices[index + 2]);
  63124. nV3 = clipVertices(nV1, vertices[index]);
  63125. result.push(nV1);
  63126. result.push(nV2);
  63127. result.push(nV3);
  63128. }
  63129. if (!v3Out) {
  63130. nV1 = vertices[index + 2].clone();
  63131. nV2 = clipVertices(nV1, vertices[index]);
  63132. nV3 = clipVertices(nV1, vertices[index + 1]);
  63133. result.push(nV1);
  63134. result.push(nV2);
  63135. result.push(nV3);
  63136. }
  63137. break;
  63138. case 3:
  63139. break;
  63140. }
  63141. }
  63142. return result;
  63143. };
  63144. for (var index = 0; index < indices.length; index += 3) {
  63145. var faceVertices = new Array();
  63146. faceVertices.push(extractDecalVector3(index));
  63147. faceVertices.push(extractDecalVector3(index + 1));
  63148. faceVertices.push(extractDecalVector3(index + 2));
  63149. // Clip
  63150. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  63151. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  63152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  63153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  63154. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  63155. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  63156. if (faceVertices.length === 0) {
  63157. continue;
  63158. }
  63159. // Add UVs and get back to world
  63160. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  63161. var vertex = faceVertices[vIndex];
  63162. //TODO check for Int32Array | Uint32Array | Uint16Array
  63163. vertexData.indices.push(currentVertexDataIndex);
  63164. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  63165. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  63166. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  63167. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  63168. currentVertexDataIndex++;
  63169. }
  63170. }
  63171. // Return mesh
  63172. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  63173. vertexData.applyToMesh(decal);
  63174. decal.position = position.clone();
  63175. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  63176. return decal;
  63177. };
  63178. // Privates
  63179. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  63180. // extrusion geometry
  63181. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  63182. var tangents = path3D.getTangents();
  63183. var normals = path3D.getNormals();
  63184. var binormals = path3D.getBinormals();
  63185. var distances = path3D.getDistances();
  63186. var angle = 0;
  63187. var returnScale = function () { return scale !== null ? scale : 1; };
  63188. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  63189. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  63190. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  63191. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63192. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63193. for (var i = 0; i < curve.length; i++) {
  63194. var shapePath = new Array();
  63195. var angleStep = rotate(i, distances[i]);
  63196. var scaleRatio = scl(i, distances[i]);
  63197. for (var p = 0; p < shape.length; p++) {
  63198. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  63199. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  63200. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  63201. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  63202. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  63203. shapePath[p] = rotated;
  63204. }
  63205. shapePaths[index] = shapePath;
  63206. angle += angleStep;
  63207. index++;
  63208. }
  63209. // cap
  63210. var capPath = function (shapePath) {
  63211. var pointCap = Array();
  63212. var barycenter = BABYLON.Vector3.Zero();
  63213. var i;
  63214. for (i = 0; i < shapePath.length; i++) {
  63215. barycenter.addInPlace(shapePath[i]);
  63216. }
  63217. barycenter.scaleInPlace(1.0 / shapePath.length);
  63218. for (i = 0; i < shapePath.length; i++) {
  63219. pointCap.push(barycenter);
  63220. }
  63221. return pointCap;
  63222. };
  63223. switch (cap) {
  63224. case BABYLON.Mesh.NO_CAP:
  63225. break;
  63226. case BABYLON.Mesh.CAP_START:
  63227. shapePaths[0] = capPath(shapePaths[2]);
  63228. shapePaths[1] = shapePaths[2];
  63229. break;
  63230. case BABYLON.Mesh.CAP_END:
  63231. shapePaths[index] = shapePaths[index - 1];
  63232. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63233. break;
  63234. case BABYLON.Mesh.CAP_ALL:
  63235. shapePaths[0] = capPath(shapePaths[2]);
  63236. shapePaths[1] = shapePaths[2];
  63237. shapePaths[index] = shapePaths[index - 1];
  63238. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  63239. break;
  63240. default:
  63241. break;
  63242. }
  63243. return shapePaths;
  63244. };
  63245. var path3D;
  63246. var pathArray;
  63247. if (instance) { // instance update
  63248. path3D = (instance.path3D).update(curve);
  63249. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  63250. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  63251. return instance;
  63252. }
  63253. // extruded shape creation
  63254. path3D = new BABYLON.Path3D(curve);
  63255. var newShapePaths = new Array();
  63256. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63257. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  63258. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  63259. extrudedGeneric.pathArray = pathArray;
  63260. extrudedGeneric.path3D = path3D;
  63261. extrudedGeneric.cap = cap;
  63262. return extrudedGeneric;
  63263. };
  63264. return MeshBuilder;
  63265. }());
  63266. BABYLON.MeshBuilder = MeshBuilder;
  63267. })(BABYLON || (BABYLON = {}));
  63268. //# sourceMappingURL=babylon.meshBuilder.js.map
  63269. var BABYLON;
  63270. (function (BABYLON) {
  63271. /**
  63272. * Draco compression (https://google.github.io/draco/)
  63273. *
  63274. * This class wraps the Draco module.
  63275. *
  63276. * **Encoder**
  63277. *
  63278. * The encoder is not currently implemented.
  63279. *
  63280. * **Decoder**
  63281. *
  63282. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  63283. *
  63284. * To update the configuration, use the following code:
  63285. * ```javascript
  63286. * BABYLON.DracoCompression.Configuration = {
  63287. * decoder: {
  63288. * wasmUrl: "<url to the WebAssembly library>",
  63289. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  63290. * fallbackUrl: "<url to the fallback JavaScript library>",
  63291. * }
  63292. * };
  63293. * ```
  63294. *
  63295. * 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.
  63296. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  63297. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  63298. *
  63299. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  63300. * ```javascript
  63301. * var dracoCompression = new BABYLON.DracoCompression();
  63302. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  63303. * [BABYLON.VertexBuffer.PositionKind]: 0
  63304. * });
  63305. * ```
  63306. *
  63307. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  63308. */
  63309. var DracoCompression = /** @class */ (function () {
  63310. /**
  63311. * Constructor
  63312. */
  63313. function DracoCompression() {
  63314. }
  63315. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  63316. /**
  63317. * Returns true if the decoder is available.
  63318. */
  63319. get: function () {
  63320. if (typeof DracoDecoderModule !== "undefined") {
  63321. return true;
  63322. }
  63323. var decoder = DracoCompression.Configuration.decoder;
  63324. if (decoder) {
  63325. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63326. return true;
  63327. }
  63328. if (decoder.fallbackUrl) {
  63329. return true;
  63330. }
  63331. }
  63332. return false;
  63333. },
  63334. enumerable: true,
  63335. configurable: true
  63336. });
  63337. /**
  63338. * Stop all async operations and release resources.
  63339. */
  63340. DracoCompression.prototype.dispose = function () {
  63341. };
  63342. /**
  63343. * Decode Draco compressed mesh data to vertex data.
  63344. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  63345. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  63346. * @returns A promise that resolves with the decoded vertex data
  63347. */
  63348. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  63349. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  63350. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  63351. var module = wrappedModule.module;
  63352. var vertexData = new BABYLON.VertexData();
  63353. var buffer = new module.DecoderBuffer();
  63354. buffer.Init(dataView, dataView.byteLength);
  63355. var decoder = new module.Decoder();
  63356. var geometry;
  63357. var status;
  63358. try {
  63359. var type = decoder.GetEncodedGeometryType(buffer);
  63360. switch (type) {
  63361. case module.TRIANGULAR_MESH:
  63362. geometry = new module.Mesh();
  63363. status = decoder.DecodeBufferToMesh(buffer, geometry);
  63364. break;
  63365. case module.POINT_CLOUD:
  63366. geometry = new module.PointCloud();
  63367. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  63368. break;
  63369. default:
  63370. throw new Error("Invalid geometry type " + type);
  63371. }
  63372. if (!status.ok() || !geometry.ptr) {
  63373. throw new Error(status.error_msg());
  63374. }
  63375. var numPoints = geometry.num_points();
  63376. if (type === module.TRIANGULAR_MESH) {
  63377. var numFaces = geometry.num_faces();
  63378. var faceIndices = new module.DracoInt32Array();
  63379. try {
  63380. var indices = new Uint32Array(numFaces * 3);
  63381. for (var i = 0; i < numFaces; i++) {
  63382. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  63383. var offset = i * 3;
  63384. indices[offset + 0] = faceIndices.GetValue(0);
  63385. indices[offset + 1] = faceIndices.GetValue(1);
  63386. indices[offset + 2] = faceIndices.GetValue(2);
  63387. }
  63388. vertexData.indices = indices;
  63389. }
  63390. finally {
  63391. module.destroy(faceIndices);
  63392. }
  63393. }
  63394. for (var kind in attributes) {
  63395. var uniqueId = attributes[kind];
  63396. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  63397. var dracoData = new module.DracoFloat32Array();
  63398. try {
  63399. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  63400. var babylonData = new Float32Array(numPoints * attribute.num_components());
  63401. for (var i = 0; i < babylonData.length; i++) {
  63402. babylonData[i] = dracoData.GetValue(i);
  63403. }
  63404. vertexData.set(babylonData, kind);
  63405. }
  63406. finally {
  63407. module.destroy(dracoData);
  63408. }
  63409. }
  63410. }
  63411. finally {
  63412. if (geometry) {
  63413. module.destroy(geometry);
  63414. }
  63415. module.destroy(decoder);
  63416. module.destroy(buffer);
  63417. }
  63418. return vertexData;
  63419. });
  63420. };
  63421. DracoCompression._GetDecoderModule = function () {
  63422. if (!DracoCompression._DecoderModulePromise) {
  63423. var promise = null;
  63424. var config_1 = {};
  63425. if (typeof DracoDecoderModule !== "undefined") {
  63426. promise = Promise.resolve();
  63427. }
  63428. else {
  63429. var decoder = DracoCompression.Configuration.decoder;
  63430. if (decoder) {
  63431. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  63432. promise = Promise.all([
  63433. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  63434. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  63435. config_1.wasmBinary = data;
  63436. })
  63437. ]);
  63438. }
  63439. else if (decoder.fallbackUrl) {
  63440. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  63441. }
  63442. }
  63443. }
  63444. if (!promise) {
  63445. throw new Error("Draco decoder module is not available");
  63446. }
  63447. DracoCompression._DecoderModulePromise = promise.then(function () {
  63448. return new Promise(function (resolve) {
  63449. config_1.onModuleLoaded = function (decoderModule) {
  63450. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  63451. resolve({ module: decoderModule });
  63452. };
  63453. DracoDecoderModule(config_1);
  63454. });
  63455. });
  63456. }
  63457. return DracoCompression._DecoderModulePromise;
  63458. };
  63459. DracoCompression._LoadScriptAsync = function (url) {
  63460. return new Promise(function (resolve, reject) {
  63461. BABYLON.Tools.LoadScript(url, function () {
  63462. resolve();
  63463. }, function (message) {
  63464. reject(new Error(message));
  63465. });
  63466. });
  63467. };
  63468. DracoCompression._LoadFileAsync = function (url) {
  63469. return new Promise(function (resolve, reject) {
  63470. BABYLON.Tools.LoadFile(url, function (data) {
  63471. resolve(data);
  63472. }, undefined, undefined, true, function (request, exception) {
  63473. reject(exception);
  63474. });
  63475. });
  63476. };
  63477. /**
  63478. * The configuration. Defaults to the following urls:
  63479. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  63480. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  63481. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63482. */
  63483. DracoCompression.Configuration = {
  63484. decoder: {
  63485. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  63486. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  63487. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  63488. }
  63489. };
  63490. return DracoCompression;
  63491. }());
  63492. BABYLON.DracoCompression = DracoCompression;
  63493. })(BABYLON || (BABYLON = {}));
  63494. //# sourceMappingURL=babylon.dracoCompression.js.map
  63495. var BABYLON;
  63496. (function (BABYLON) {
  63497. var AudioEngine = /** @class */ (function () {
  63498. function AudioEngine() {
  63499. this._audioContext = null;
  63500. this._audioContextInitialized = false;
  63501. this.canUseWebAudio = false;
  63502. this.WarnedWebAudioUnsupported = false;
  63503. this.unlocked = false;
  63504. this.isMP3supported = false;
  63505. this.isOGGsupported = false;
  63506. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  63507. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  63508. this.canUseWebAudio = true;
  63509. }
  63510. var audioElem = document.createElement('audio');
  63511. try {
  63512. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  63513. this.isMP3supported = true;
  63514. }
  63515. }
  63516. catch (e) {
  63517. // protect error during capability check.
  63518. }
  63519. try {
  63520. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  63521. this.isOGGsupported = true;
  63522. }
  63523. }
  63524. catch (e) {
  63525. // protect error during capability check.
  63526. }
  63527. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  63528. this._unlockiOSaudio();
  63529. }
  63530. else {
  63531. this.unlocked = true;
  63532. }
  63533. }
  63534. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  63535. get: function () {
  63536. if (!this._audioContextInitialized) {
  63537. this._initializeAudioContext();
  63538. }
  63539. return this._audioContext;
  63540. },
  63541. enumerable: true,
  63542. configurable: true
  63543. });
  63544. AudioEngine.prototype._unlockiOSaudio = function () {
  63545. var _this = this;
  63546. var unlockaudio = function () {
  63547. if (!_this.audioContext) {
  63548. return;
  63549. }
  63550. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  63551. var source = _this.audioContext.createBufferSource();
  63552. source.buffer = buffer;
  63553. source.connect(_this.audioContext.destination);
  63554. source.start(0);
  63555. setTimeout(function () {
  63556. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  63557. _this.unlocked = true;
  63558. window.removeEventListener('touchend', unlockaudio, false);
  63559. if (_this.onAudioUnlocked) {
  63560. _this.onAudioUnlocked();
  63561. }
  63562. }
  63563. }, 0);
  63564. };
  63565. window.addEventListener('touchend', unlockaudio, false);
  63566. };
  63567. AudioEngine.prototype._initializeAudioContext = function () {
  63568. try {
  63569. if (this.canUseWebAudio) {
  63570. this._audioContext = new AudioContext();
  63571. // create a global volume gain node
  63572. this.masterGain = this._audioContext.createGain();
  63573. this.masterGain.gain.value = 1;
  63574. this.masterGain.connect(this._audioContext.destination);
  63575. this._audioContextInitialized = true;
  63576. }
  63577. }
  63578. catch (e) {
  63579. this.canUseWebAudio = false;
  63580. BABYLON.Tools.Error("Web Audio: " + e.message);
  63581. }
  63582. };
  63583. AudioEngine.prototype.dispose = function () {
  63584. if (this.canUseWebAudio && this._audioContextInitialized) {
  63585. if (this._connectedAnalyser && this._audioContext) {
  63586. this._connectedAnalyser.stopDebugCanvas();
  63587. this._connectedAnalyser.dispose();
  63588. this.masterGain.disconnect();
  63589. this.masterGain.connect(this._audioContext.destination);
  63590. this._connectedAnalyser = null;
  63591. }
  63592. this.masterGain.gain.value = 1;
  63593. }
  63594. this.WarnedWebAudioUnsupported = false;
  63595. };
  63596. AudioEngine.prototype.getGlobalVolume = function () {
  63597. if (this.canUseWebAudio && this._audioContextInitialized) {
  63598. return this.masterGain.gain.value;
  63599. }
  63600. else {
  63601. return -1;
  63602. }
  63603. };
  63604. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  63605. if (this.canUseWebAudio && this._audioContextInitialized) {
  63606. this.masterGain.gain.value = newVolume;
  63607. }
  63608. };
  63609. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  63610. if (this._connectedAnalyser) {
  63611. this._connectedAnalyser.stopDebugCanvas();
  63612. }
  63613. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  63614. this._connectedAnalyser = analyser;
  63615. this.masterGain.disconnect();
  63616. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  63617. }
  63618. };
  63619. return AudioEngine;
  63620. }());
  63621. BABYLON.AudioEngine = AudioEngine;
  63622. })(BABYLON || (BABYLON = {}));
  63623. //# sourceMappingURL=babylon.audioEngine.js.map
  63624. var BABYLON;
  63625. (function (BABYLON) {
  63626. var Sound = /** @class */ (function () {
  63627. /**
  63628. * Create a sound and attach it to a scene
  63629. * @param name Name of your sound
  63630. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  63631. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  63632. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  63633. */
  63634. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  63635. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  63636. var _this = this;
  63637. this.autoplay = false;
  63638. this.loop = false;
  63639. this.useCustomAttenuation = false;
  63640. this.spatialSound = false;
  63641. this.refDistance = 1;
  63642. this.rolloffFactor = 1;
  63643. this.maxDistance = 100;
  63644. this.distanceModel = "linear";
  63645. this._panningModel = "equalpower";
  63646. this._playbackRate = 1;
  63647. this._streaming = false;
  63648. this._startTime = 0;
  63649. this._startOffset = 0;
  63650. this._position = BABYLON.Vector3.Zero();
  63651. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  63652. this._volume = 1;
  63653. this._isReadyToPlay = false;
  63654. this.isPlaying = false;
  63655. this.isPaused = false;
  63656. this._isDirectional = false;
  63657. // Used if you'd like to create a directional sound.
  63658. // If not set, the sound will be omnidirectional
  63659. this._coneInnerAngle = 360;
  63660. this._coneOuterAngle = 360;
  63661. this._coneOuterGain = 0;
  63662. this._isOutputConnected = false;
  63663. this._urlType = "Unknown";
  63664. this.name = name;
  63665. this._scene = scene;
  63666. this._readyToPlayCallback = readyToPlayCallback;
  63667. // Default custom attenuation function is a linear attenuation
  63668. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  63669. if (currentDistance < maxDistance) {
  63670. return currentVolume * (1 - currentDistance / maxDistance);
  63671. }
  63672. else {
  63673. return 0;
  63674. }
  63675. };
  63676. if (options) {
  63677. this.autoplay = options.autoplay || false;
  63678. this.loop = options.loop || false;
  63679. // if volume === 0, we need another way to check this option
  63680. if (options.volume !== undefined) {
  63681. this._volume = options.volume;
  63682. }
  63683. this.spatialSound = options.spatialSound || false;
  63684. this.maxDistance = options.maxDistance || 100;
  63685. this.useCustomAttenuation = options.useCustomAttenuation || false;
  63686. this.rolloffFactor = options.rolloffFactor || 1;
  63687. this.refDistance = options.refDistance || 1;
  63688. this.distanceModel = options.distanceModel || "linear";
  63689. this._playbackRate = options.playbackRate || 1;
  63690. this._streaming = options.streaming || false;
  63691. }
  63692. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63693. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  63694. this._soundGain.gain.value = this._volume;
  63695. this._inputAudioNode = this._soundGain;
  63696. this._ouputAudioNode = this._soundGain;
  63697. if (this.spatialSound) {
  63698. this._createSpatialParameters();
  63699. }
  63700. this._scene.mainSoundTrack.AddSound(this);
  63701. var validParameter = true;
  63702. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  63703. if (urlOrArrayBuffer) {
  63704. try {
  63705. if (typeof (urlOrArrayBuffer) === "string") {
  63706. this._urlType = "String";
  63707. }
  63708. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  63709. this._urlType = "ArrayBuffer";
  63710. }
  63711. else if (urlOrArrayBuffer instanceof MediaStream) {
  63712. this._urlType = "MediaStream";
  63713. }
  63714. else if (Array.isArray(urlOrArrayBuffer)) {
  63715. this._urlType = "Array";
  63716. }
  63717. var urls = [];
  63718. var codecSupportedFound = false;
  63719. switch (this._urlType) {
  63720. case "MediaStream":
  63721. this._streaming = true;
  63722. this._isReadyToPlay = true;
  63723. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  63724. if (this.autoplay) {
  63725. this.play();
  63726. }
  63727. if (this._readyToPlayCallback) {
  63728. this._readyToPlayCallback();
  63729. }
  63730. break;
  63731. case "ArrayBuffer":
  63732. if (urlOrArrayBuffer.byteLength > 0) {
  63733. codecSupportedFound = true;
  63734. this._soundLoaded(urlOrArrayBuffer);
  63735. }
  63736. break;
  63737. case "String":
  63738. urls.push(urlOrArrayBuffer);
  63739. case "Array":
  63740. if (urls.length === 0)
  63741. urls = urlOrArrayBuffer;
  63742. // If we found a supported format, we load it immediately and stop the loop
  63743. for (var i = 0; i < urls.length; i++) {
  63744. var url = urls[i];
  63745. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  63746. codecSupportedFound = true;
  63747. }
  63748. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  63749. codecSupportedFound = true;
  63750. }
  63751. if (url.indexOf(".wav", url.length - 4) !== -1) {
  63752. codecSupportedFound = true;
  63753. }
  63754. if (url.indexOf("blob:") !== -1) {
  63755. codecSupportedFound = true;
  63756. }
  63757. if (codecSupportedFound) {
  63758. // Loading sound using XHR2
  63759. if (!this._streaming) {
  63760. this._scene._loadFile(url, function (data) {
  63761. _this._soundLoaded(data);
  63762. }, undefined, true, true, function (exception) {
  63763. if (exception) {
  63764. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  63765. }
  63766. BABYLON.Tools.Error("Sound creation aborted.");
  63767. _this._scene.mainSoundTrack.RemoveSound(_this);
  63768. });
  63769. }
  63770. // Streaming sound using HTML5 Audio tag
  63771. else {
  63772. this._htmlAudioElement = new Audio(url);
  63773. this._htmlAudioElement.controls = false;
  63774. this._htmlAudioElement.loop = this.loop;
  63775. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  63776. this._htmlAudioElement.preload = "auto";
  63777. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  63778. _this._isReadyToPlay = true;
  63779. if (_this.autoplay) {
  63780. _this.play();
  63781. }
  63782. if (_this._readyToPlayCallback) {
  63783. _this._readyToPlayCallback();
  63784. }
  63785. });
  63786. document.body.appendChild(this._htmlAudioElement);
  63787. }
  63788. break;
  63789. }
  63790. }
  63791. break;
  63792. default:
  63793. validParameter = false;
  63794. break;
  63795. }
  63796. if (!validParameter) {
  63797. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  63798. }
  63799. else {
  63800. if (!codecSupportedFound) {
  63801. this._isReadyToPlay = true;
  63802. // Simulating a ready to play event to avoid breaking code path
  63803. if (this._readyToPlayCallback) {
  63804. window.setTimeout(function () {
  63805. if (_this._readyToPlayCallback) {
  63806. _this._readyToPlayCallback();
  63807. }
  63808. }, 1000);
  63809. }
  63810. }
  63811. }
  63812. }
  63813. catch (ex) {
  63814. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  63815. this._scene.mainSoundTrack.RemoveSound(this);
  63816. }
  63817. }
  63818. }
  63819. else {
  63820. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  63821. this._scene.mainSoundTrack.AddSound(this);
  63822. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  63823. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  63824. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  63825. }
  63826. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  63827. if (this._readyToPlayCallback) {
  63828. window.setTimeout(function () {
  63829. if (_this._readyToPlayCallback) {
  63830. _this._readyToPlayCallback();
  63831. }
  63832. }, 1000);
  63833. }
  63834. }
  63835. }
  63836. Sound.prototype.dispose = function () {
  63837. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63838. if (this.isPlaying) {
  63839. this.stop();
  63840. }
  63841. this._isReadyToPlay = false;
  63842. if (this.soundTrackId === -1) {
  63843. this._scene.mainSoundTrack.RemoveSound(this);
  63844. }
  63845. else {
  63846. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  63847. }
  63848. if (this._soundGain) {
  63849. this._soundGain.disconnect();
  63850. this._soundGain = null;
  63851. }
  63852. if (this._soundPanner) {
  63853. this._soundPanner.disconnect();
  63854. this._soundPanner = null;
  63855. }
  63856. if (this._soundSource) {
  63857. this._soundSource.disconnect();
  63858. this._soundSource = null;
  63859. }
  63860. this._audioBuffer = null;
  63861. if (this._htmlAudioElement) {
  63862. this._htmlAudioElement.pause();
  63863. this._htmlAudioElement.src = "";
  63864. document.body.removeChild(this._htmlAudioElement);
  63865. }
  63866. if (this._streamingSource) {
  63867. this._streamingSource.disconnect();
  63868. }
  63869. if (this._connectedMesh && this._registerFunc) {
  63870. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63871. this._connectedMesh = null;
  63872. }
  63873. }
  63874. };
  63875. Sound.prototype.isReady = function () {
  63876. return this._isReadyToPlay;
  63877. };
  63878. Sound.prototype._soundLoaded = function (audioData) {
  63879. var _this = this;
  63880. if (!BABYLON.Engine.audioEngine.audioContext) {
  63881. return;
  63882. }
  63883. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  63884. _this._audioBuffer = buffer;
  63885. _this._isReadyToPlay = true;
  63886. if (_this.autoplay) {
  63887. _this.play();
  63888. }
  63889. if (_this._readyToPlayCallback) {
  63890. _this._readyToPlayCallback();
  63891. }
  63892. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  63893. };
  63894. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  63895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63896. this._audioBuffer = audioBuffer;
  63897. this._isReadyToPlay = true;
  63898. }
  63899. };
  63900. Sound.prototype.updateOptions = function (options) {
  63901. if (options) {
  63902. this.loop = options.loop || this.loop;
  63903. this.maxDistance = options.maxDistance || this.maxDistance;
  63904. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  63905. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  63906. this.refDistance = options.refDistance || this.refDistance;
  63907. this.distanceModel = options.distanceModel || this.distanceModel;
  63908. this._playbackRate = options.playbackRate || this._playbackRate;
  63909. this._updateSpatialParameters();
  63910. if (this.isPlaying) {
  63911. if (this._streaming && this._htmlAudioElement) {
  63912. this._htmlAudioElement.playbackRate = this._playbackRate;
  63913. }
  63914. else {
  63915. if (this._soundSource) {
  63916. this._soundSource.playbackRate.value = this._playbackRate;
  63917. }
  63918. }
  63919. }
  63920. }
  63921. };
  63922. Sound.prototype._createSpatialParameters = function () {
  63923. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63924. if (this._scene.headphone) {
  63925. this._panningModel = "HRTF";
  63926. }
  63927. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  63928. this._updateSpatialParameters();
  63929. this._soundPanner.connect(this._ouputAudioNode);
  63930. this._inputAudioNode = this._soundPanner;
  63931. }
  63932. };
  63933. Sound.prototype._updateSpatialParameters = function () {
  63934. if (this.spatialSound && this._soundPanner) {
  63935. if (this.useCustomAttenuation) {
  63936. // Tricks to disable in a way embedded Web Audio attenuation
  63937. this._soundPanner.distanceModel = "linear";
  63938. this._soundPanner.maxDistance = Number.MAX_VALUE;
  63939. this._soundPanner.refDistance = 1;
  63940. this._soundPanner.rolloffFactor = 1;
  63941. this._soundPanner.panningModel = this._panningModel;
  63942. }
  63943. else {
  63944. this._soundPanner.distanceModel = this.distanceModel;
  63945. this._soundPanner.maxDistance = this.maxDistance;
  63946. this._soundPanner.refDistance = this.refDistance;
  63947. this._soundPanner.rolloffFactor = this.rolloffFactor;
  63948. this._soundPanner.panningModel = this._panningModel;
  63949. }
  63950. }
  63951. };
  63952. Sound.prototype.switchPanningModelToHRTF = function () {
  63953. this._panningModel = "HRTF";
  63954. this._switchPanningModel();
  63955. };
  63956. Sound.prototype.switchPanningModelToEqualPower = function () {
  63957. this._panningModel = "equalpower";
  63958. this._switchPanningModel();
  63959. };
  63960. Sound.prototype._switchPanningModel = function () {
  63961. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63962. this._soundPanner.panningModel = this._panningModel;
  63963. }
  63964. };
  63965. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  63966. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63967. if (this._isOutputConnected) {
  63968. this._ouputAudioNode.disconnect();
  63969. }
  63970. this._ouputAudioNode.connect(soundTrackAudioNode);
  63971. this._isOutputConnected = true;
  63972. }
  63973. };
  63974. /**
  63975. * Transform this sound into a directional source
  63976. * @param coneInnerAngle Size of the inner cone in degree
  63977. * @param coneOuterAngle Size of the outer cone in degree
  63978. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  63979. */
  63980. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  63981. if (coneOuterAngle < coneInnerAngle) {
  63982. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  63983. return;
  63984. }
  63985. this._coneInnerAngle = coneInnerAngle;
  63986. this._coneOuterAngle = coneOuterAngle;
  63987. this._coneOuterGain = coneOuterGain;
  63988. this._isDirectional = true;
  63989. if (this.isPlaying && this.loop) {
  63990. this.stop();
  63991. this.play();
  63992. }
  63993. };
  63994. Sound.prototype.setPosition = function (newPosition) {
  63995. this._position = newPosition;
  63996. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  63997. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  63998. }
  63999. };
  64000. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  64001. this._localDirection = newLocalDirection;
  64002. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  64003. this._updateDirection();
  64004. }
  64005. };
  64006. Sound.prototype._updateDirection = function () {
  64007. if (!this._connectedMesh || !this._soundPanner) {
  64008. return;
  64009. }
  64010. var mat = this._connectedMesh.getWorldMatrix();
  64011. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  64012. direction.normalize();
  64013. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  64014. };
  64015. Sound.prototype.updateDistanceFromListener = function () {
  64016. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  64017. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  64018. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  64019. }
  64020. };
  64021. Sound.prototype.setAttenuationFunction = function (callback) {
  64022. this._customAttenuationFunction = callback;
  64023. };
  64024. /**
  64025. * Play the sound
  64026. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  64027. * @param offset (optional) Start the sound setting it at a specific time
  64028. */
  64029. Sound.prototype.play = function (time, offset) {
  64030. var _this = this;
  64031. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  64032. try {
  64033. if (this._startOffset < 0) {
  64034. time = -this._startOffset;
  64035. this._startOffset = 0;
  64036. }
  64037. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64038. if (!this._soundSource || !this._streamingSource) {
  64039. if (this.spatialSound && this._soundPanner) {
  64040. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  64041. if (this._isDirectional) {
  64042. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64043. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  64044. this._soundPanner.coneOuterGain = this._coneOuterGain;
  64045. if (this._connectedMesh) {
  64046. this._updateDirection();
  64047. }
  64048. else {
  64049. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  64050. }
  64051. }
  64052. }
  64053. }
  64054. if (this._streaming) {
  64055. if (!this._streamingSource) {
  64056. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  64057. this._htmlAudioElement.onended = function () { _this._onended(); };
  64058. this._htmlAudioElement.playbackRate = this._playbackRate;
  64059. }
  64060. this._streamingSource.disconnect();
  64061. this._streamingSource.connect(this._inputAudioNode);
  64062. if (this._htmlAudioElement) {
  64063. this._htmlAudioElement.play();
  64064. }
  64065. }
  64066. else {
  64067. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  64068. this._soundSource.buffer = this._audioBuffer;
  64069. this._soundSource.connect(this._inputAudioNode);
  64070. this._soundSource.loop = this.loop;
  64071. this._soundSource.playbackRate.value = this._playbackRate;
  64072. this._soundSource.onended = function () { _this._onended(); };
  64073. if (this._soundSource.buffer) {
  64074. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  64075. }
  64076. }
  64077. this._startTime = startTime;
  64078. this.isPlaying = true;
  64079. this.isPaused = false;
  64080. }
  64081. catch (ex) {
  64082. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  64083. }
  64084. }
  64085. };
  64086. Sound.prototype._onended = function () {
  64087. this.isPlaying = false;
  64088. if (this.onended) {
  64089. this.onended();
  64090. }
  64091. };
  64092. /**
  64093. * Stop the sound
  64094. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  64095. */
  64096. Sound.prototype.stop = function (time) {
  64097. if (this.isPlaying) {
  64098. if (this._streaming) {
  64099. if (this._htmlAudioElement) {
  64100. this._htmlAudioElement.pause();
  64101. // Test needed for Firefox or it will generate an Invalid State Error
  64102. if (this._htmlAudioElement.currentTime > 0) {
  64103. this._htmlAudioElement.currentTime = 0;
  64104. }
  64105. }
  64106. else {
  64107. this._streamingSource.disconnect();
  64108. }
  64109. }
  64110. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  64111. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  64112. this._soundSource.stop(stopTime);
  64113. this._soundSource.onended = function () { };
  64114. if (!this.isPaused) {
  64115. this._startOffset = 0;
  64116. }
  64117. }
  64118. this.isPlaying = false;
  64119. }
  64120. };
  64121. Sound.prototype.pause = function () {
  64122. if (this.isPlaying) {
  64123. this.isPaused = true;
  64124. if (this._streaming) {
  64125. if (this._htmlAudioElement) {
  64126. this._htmlAudioElement.pause();
  64127. }
  64128. else {
  64129. this._streamingSource.disconnect();
  64130. }
  64131. }
  64132. else if (BABYLON.Engine.audioEngine.audioContext) {
  64133. this.stop(0);
  64134. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  64135. }
  64136. }
  64137. };
  64138. Sound.prototype.setVolume = function (newVolume, time) {
  64139. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  64140. if (time && BABYLON.Engine.audioEngine.audioContext) {
  64141. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  64142. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  64143. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  64144. }
  64145. else {
  64146. this._soundGain.gain.value = newVolume;
  64147. }
  64148. }
  64149. this._volume = newVolume;
  64150. };
  64151. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  64152. this._playbackRate = newPlaybackRate;
  64153. if (this.isPlaying) {
  64154. if (this._streaming && this._htmlAudioElement) {
  64155. this._htmlAudioElement.playbackRate = this._playbackRate;
  64156. }
  64157. else if (this._soundSource) {
  64158. this._soundSource.playbackRate.value = this._playbackRate;
  64159. }
  64160. }
  64161. };
  64162. Sound.prototype.getVolume = function () {
  64163. return this._volume;
  64164. };
  64165. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  64166. var _this = this;
  64167. if (this._connectedMesh && this._registerFunc) {
  64168. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64169. this._registerFunc = null;
  64170. }
  64171. this._connectedMesh = meshToConnectTo;
  64172. if (!this.spatialSound) {
  64173. this.spatialSound = true;
  64174. this._createSpatialParameters();
  64175. if (this.isPlaying && this.loop) {
  64176. this.stop();
  64177. this.play();
  64178. }
  64179. }
  64180. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  64181. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  64182. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  64183. };
  64184. Sound.prototype.detachFromMesh = function () {
  64185. if (this._connectedMesh && this._registerFunc) {
  64186. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64187. this._registerFunc = null;
  64188. this._connectedMesh = null;
  64189. }
  64190. };
  64191. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  64192. if (!node.getBoundingInfo) {
  64193. return;
  64194. }
  64195. var mesh = node;
  64196. var boundingInfo = mesh.getBoundingInfo();
  64197. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  64198. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  64199. this._updateDirection();
  64200. }
  64201. };
  64202. Sound.prototype.clone = function () {
  64203. var _this = this;
  64204. if (!this._streaming) {
  64205. var setBufferAndRun = function () {
  64206. if (_this._isReadyToPlay) {
  64207. clonedSound._audioBuffer = _this.getAudioBuffer();
  64208. clonedSound._isReadyToPlay = true;
  64209. if (clonedSound.autoplay) {
  64210. clonedSound.play();
  64211. }
  64212. }
  64213. else {
  64214. window.setTimeout(setBufferAndRun, 300);
  64215. }
  64216. };
  64217. var currentOptions = {
  64218. autoplay: this.autoplay, loop: this.loop,
  64219. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  64220. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  64221. refDistance: this.refDistance, distanceModel: this.distanceModel
  64222. };
  64223. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  64224. if (this.useCustomAttenuation) {
  64225. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  64226. }
  64227. clonedSound.setPosition(this._position);
  64228. clonedSound.setPlaybackRate(this._playbackRate);
  64229. setBufferAndRun();
  64230. return clonedSound;
  64231. }
  64232. // Can't clone a streaming sound
  64233. else {
  64234. return null;
  64235. }
  64236. };
  64237. Sound.prototype.getAudioBuffer = function () {
  64238. return this._audioBuffer;
  64239. };
  64240. Sound.prototype.serialize = function () {
  64241. var serializationObject = {
  64242. name: this.name,
  64243. url: this.name,
  64244. autoplay: this.autoplay,
  64245. loop: this.loop,
  64246. volume: this._volume,
  64247. spatialSound: this.spatialSound,
  64248. maxDistance: this.maxDistance,
  64249. rolloffFactor: this.rolloffFactor,
  64250. refDistance: this.refDistance,
  64251. distanceModel: this.distanceModel,
  64252. playbackRate: this._playbackRate,
  64253. panningModel: this._panningModel,
  64254. soundTrackId: this.soundTrackId
  64255. };
  64256. if (this.spatialSound) {
  64257. if (this._connectedMesh)
  64258. serializationObject.connectedMeshId = this._connectedMesh.id;
  64259. serializationObject.position = this._position.asArray();
  64260. serializationObject.refDistance = this.refDistance;
  64261. serializationObject.distanceModel = this.distanceModel;
  64262. serializationObject.isDirectional = this._isDirectional;
  64263. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  64264. serializationObject.coneInnerAngle = this._coneInnerAngle;
  64265. serializationObject.coneOuterAngle = this._coneOuterAngle;
  64266. serializationObject.coneOuterGain = this._coneOuterGain;
  64267. }
  64268. return serializationObject;
  64269. };
  64270. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  64271. var soundName = parsedSound.name;
  64272. var soundUrl;
  64273. if (parsedSound.url) {
  64274. soundUrl = rootUrl + parsedSound.url;
  64275. }
  64276. else {
  64277. soundUrl = rootUrl + soundName;
  64278. }
  64279. var options = {
  64280. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  64281. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  64282. rolloffFactor: parsedSound.rolloffFactor,
  64283. refDistance: parsedSound.refDistance,
  64284. distanceModel: parsedSound.distanceModel,
  64285. playbackRate: parsedSound.playbackRate
  64286. };
  64287. var newSound;
  64288. if (!sourceSound) {
  64289. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  64290. scene._addPendingData(newSound);
  64291. }
  64292. else {
  64293. var setBufferAndRun = function () {
  64294. if (sourceSound._isReadyToPlay) {
  64295. newSound._audioBuffer = sourceSound.getAudioBuffer();
  64296. newSound._isReadyToPlay = true;
  64297. if (newSound.autoplay) {
  64298. newSound.play();
  64299. }
  64300. }
  64301. else {
  64302. window.setTimeout(setBufferAndRun, 300);
  64303. }
  64304. };
  64305. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  64306. setBufferAndRun();
  64307. }
  64308. if (parsedSound.position) {
  64309. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  64310. newSound.setPosition(soundPosition);
  64311. }
  64312. if (parsedSound.isDirectional) {
  64313. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  64314. if (parsedSound.localDirectionToMesh) {
  64315. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  64316. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  64317. }
  64318. }
  64319. if (parsedSound.connectedMeshId) {
  64320. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  64321. if (connectedMesh) {
  64322. newSound.attachToMesh(connectedMesh);
  64323. }
  64324. }
  64325. return newSound;
  64326. };
  64327. return Sound;
  64328. }());
  64329. BABYLON.Sound = Sound;
  64330. })(BABYLON || (BABYLON = {}));
  64331. //# sourceMappingURL=babylon.sound.js.map
  64332. var BABYLON;
  64333. (function (BABYLON) {
  64334. var SoundTrack = /** @class */ (function () {
  64335. function SoundTrack(scene, options) {
  64336. this.id = -1;
  64337. this._isMainTrack = false;
  64338. this._isInitialized = false;
  64339. this._scene = scene;
  64340. this.soundCollection = new Array();
  64341. this._options = options;
  64342. if (!this._isMainTrack) {
  64343. this._scene.soundTracks.push(this);
  64344. this.id = this._scene.soundTracks.length - 1;
  64345. }
  64346. }
  64347. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  64348. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64349. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  64350. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  64351. if (this._options) {
  64352. if (this._options.volume) {
  64353. this._outputAudioNode.gain.value = this._options.volume;
  64354. }
  64355. if (this._options.mainTrack) {
  64356. this._isMainTrack = this._options.mainTrack;
  64357. }
  64358. }
  64359. this._isInitialized = true;
  64360. }
  64361. };
  64362. SoundTrack.prototype.dispose = function () {
  64363. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  64364. if (this._connectedAnalyser) {
  64365. this._connectedAnalyser.stopDebugCanvas();
  64366. }
  64367. while (this.soundCollection.length) {
  64368. this.soundCollection[0].dispose();
  64369. }
  64370. if (this._outputAudioNode) {
  64371. this._outputAudioNode.disconnect();
  64372. }
  64373. this._outputAudioNode = null;
  64374. }
  64375. };
  64376. SoundTrack.prototype.AddSound = function (sound) {
  64377. if (!this._isInitialized) {
  64378. this._initializeSoundTrackAudioGraph();
  64379. }
  64380. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64381. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  64382. }
  64383. if (sound.soundTrackId) {
  64384. if (sound.soundTrackId === -1) {
  64385. this._scene.mainSoundTrack.RemoveSound(sound);
  64386. }
  64387. else {
  64388. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  64389. }
  64390. }
  64391. this.soundCollection.push(sound);
  64392. sound.soundTrackId = this.id;
  64393. };
  64394. SoundTrack.prototype.RemoveSound = function (sound) {
  64395. var index = this.soundCollection.indexOf(sound);
  64396. if (index !== -1) {
  64397. this.soundCollection.splice(index, 1);
  64398. }
  64399. };
  64400. SoundTrack.prototype.setVolume = function (newVolume) {
  64401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64402. this._outputAudioNode.gain.value = newVolume;
  64403. }
  64404. };
  64405. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  64406. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64407. for (var i = 0; i < this.soundCollection.length; i++) {
  64408. this.soundCollection[i].switchPanningModelToHRTF();
  64409. }
  64410. }
  64411. };
  64412. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  64413. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64414. for (var i = 0; i < this.soundCollection.length; i++) {
  64415. this.soundCollection[i].switchPanningModelToEqualPower();
  64416. }
  64417. }
  64418. };
  64419. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  64420. if (this._connectedAnalyser) {
  64421. this._connectedAnalyser.stopDebugCanvas();
  64422. }
  64423. this._connectedAnalyser = analyser;
  64424. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  64425. this._outputAudioNode.disconnect();
  64426. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  64427. }
  64428. };
  64429. return SoundTrack;
  64430. }());
  64431. BABYLON.SoundTrack = SoundTrack;
  64432. })(BABYLON || (BABYLON = {}));
  64433. //# sourceMappingURL=babylon.soundtrack.js.map
  64434. var BABYLON;
  64435. (function (BABYLON) {
  64436. /**
  64437. * Class used to work with sound analyzer using fast fourier transform (FFT)
  64438. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  64439. */
  64440. var Analyser = /** @class */ (function () {
  64441. /**
  64442. * Creates a new analyser
  64443. * @param scene defines hosting scene
  64444. */
  64445. function Analyser(scene) {
  64446. /**
  64447. * Gets or sets the smoothing
  64448. * @ignorenaming
  64449. */
  64450. this.SMOOTHING = 0.75;
  64451. /**
  64452. * Gets or sets the FFT table size
  64453. * @ignorenaming
  64454. */
  64455. this.FFT_SIZE = 512;
  64456. /**
  64457. * Gets or sets the bar graph amplitude
  64458. * @ignorenaming
  64459. */
  64460. this.BARGRAPHAMPLITUDE = 256;
  64461. /**
  64462. * Gets or sets the position of the debug canvas
  64463. * @ignorenaming
  64464. */
  64465. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  64466. /**
  64467. * Gets or sets the debug canvas size
  64468. * @ignorenaming
  64469. */
  64470. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  64471. this._scene = scene;
  64472. this._audioEngine = BABYLON.Engine.audioEngine;
  64473. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  64474. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  64475. this._webAudioAnalyser.minDecibels = -140;
  64476. this._webAudioAnalyser.maxDecibels = 0;
  64477. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64478. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  64479. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  64480. }
  64481. }
  64482. /**
  64483. * Get the number of data values you will have to play with for the visualization
  64484. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  64485. * @returns a number
  64486. */
  64487. Analyser.prototype.getFrequencyBinCount = function () {
  64488. if (this._audioEngine.canUseWebAudio) {
  64489. return this._webAudioAnalyser.frequencyBinCount;
  64490. }
  64491. else {
  64492. return 0;
  64493. }
  64494. };
  64495. /**
  64496. * Gets the current frequency data as a byte array
  64497. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64498. * @returns a Uint8Array
  64499. */
  64500. Analyser.prototype.getByteFrequencyData = function () {
  64501. if (this._audioEngine.canUseWebAudio) {
  64502. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64503. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64504. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  64505. }
  64506. return this._byteFreqs;
  64507. };
  64508. /**
  64509. * Gets the current waveform as a byte array
  64510. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  64511. * @returns a Uint8Array
  64512. */
  64513. Analyser.prototype.getByteTimeDomainData = function () {
  64514. if (this._audioEngine.canUseWebAudio) {
  64515. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64516. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64517. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  64518. }
  64519. return this._byteTime;
  64520. };
  64521. /**
  64522. * Gets the current frequency data as a float array
  64523. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  64524. * @returns a Float32Array
  64525. */
  64526. Analyser.prototype.getFloatFrequencyData = function () {
  64527. if (this._audioEngine.canUseWebAudio) {
  64528. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  64529. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  64530. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  64531. }
  64532. return this._floatFreqs;
  64533. };
  64534. /**
  64535. * Renders the debug canvas
  64536. */
  64537. Analyser.prototype.drawDebugCanvas = function () {
  64538. var _this = this;
  64539. if (this._audioEngine.canUseWebAudio) {
  64540. if (!this._debugCanvas) {
  64541. this._debugCanvas = document.createElement("canvas");
  64542. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  64543. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  64544. this._debugCanvas.style.position = "absolute";
  64545. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  64546. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  64547. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  64548. document.body.appendChild(this._debugCanvas);
  64549. this._registerFunc = function () {
  64550. _this.drawDebugCanvas();
  64551. };
  64552. this._scene.registerBeforeRender(this._registerFunc);
  64553. }
  64554. if (this._registerFunc && this._debugCanvasContext) {
  64555. var workingArray = this.getByteFrequencyData();
  64556. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  64557. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  64558. // Draw the frequency domain chart.
  64559. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  64560. var value = workingArray[i];
  64561. var percent = value / this.BARGRAPHAMPLITUDE;
  64562. var height = this.DEBUGCANVASSIZE.height * percent;
  64563. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  64564. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  64565. var hue = i / this.getFrequencyBinCount() * 360;
  64566. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  64567. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  64568. }
  64569. }
  64570. }
  64571. };
  64572. /**
  64573. * Stops rendering the debug canvas and removes it
  64574. */
  64575. Analyser.prototype.stopDebugCanvas = function () {
  64576. if (this._debugCanvas) {
  64577. if (this._registerFunc) {
  64578. this._scene.unregisterBeforeRender(this._registerFunc);
  64579. this._registerFunc = null;
  64580. }
  64581. document.body.removeChild(this._debugCanvas);
  64582. this._debugCanvas = null;
  64583. this._debugCanvasContext = null;
  64584. }
  64585. };
  64586. /**
  64587. * Connects two audio nodes
  64588. * @param inputAudioNode defines first node to connect
  64589. * @param outputAudioNode defines second node to connect
  64590. */
  64591. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  64592. if (this._audioEngine.canUseWebAudio) {
  64593. inputAudioNode.connect(this._webAudioAnalyser);
  64594. this._webAudioAnalyser.connect(outputAudioNode);
  64595. }
  64596. };
  64597. /**
  64598. * Releases all associated resources
  64599. */
  64600. Analyser.prototype.dispose = function () {
  64601. if (this._audioEngine.canUseWebAudio) {
  64602. this._webAudioAnalyser.disconnect();
  64603. }
  64604. };
  64605. return Analyser;
  64606. }());
  64607. BABYLON.Analyser = Analyser;
  64608. })(BABYLON || (BABYLON = {}));
  64609. //# sourceMappingURL=babylon.analyser.js.map
  64610. var BABYLON;
  64611. (function (BABYLON) {
  64612. var CubeTexture = /** @class */ (function (_super) {
  64613. __extends(CubeTexture, _super);
  64614. /**
  64615. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  64616. * as prefiltered data.
  64617. * @param rootUrl defines the url of the texture or the root name of the six images
  64618. * @param scene defines the scene the texture is attached to
  64619. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  64620. * @param noMipmap defines if mipmaps should be created or not
  64621. * @param files defines the six files to load for the different faces
  64622. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  64623. * @param onError defines a callback triggered in case of error during load
  64624. * @param format defines the internal format to use for the texture once loaded
  64625. * @param prefiltered defines whether or not the texture is created from prefiltered data
  64626. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  64627. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64628. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64629. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64630. * @return the cube texture
  64631. */
  64632. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  64633. if (extensions === void 0) { extensions = null; }
  64634. if (noMipmap === void 0) { noMipmap = false; }
  64635. if (files === void 0) { files = null; }
  64636. if (onLoad === void 0) { onLoad = null; }
  64637. if (onError === void 0) { onError = null; }
  64638. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64639. if (prefiltered === void 0) { prefiltered = false; }
  64640. if (forcedExtension === void 0) { forcedExtension = null; }
  64641. if (createPolynomials === void 0) { createPolynomials = false; }
  64642. if (lodScale === void 0) { lodScale = 0.8; }
  64643. if (lodOffset === void 0) { lodOffset = 0; }
  64644. var _this = _super.call(this, scene) || this;
  64645. /**
  64646. * Gets or sets the center of the bounding box associated with the cube texture
  64647. * It must define where the camera used to render the texture was set
  64648. */
  64649. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64650. _this._rotationY = 0;
  64651. /** @hidden */
  64652. _this._prefiltered = false;
  64653. _this.name = rootUrl;
  64654. _this.url = rootUrl;
  64655. _this._noMipmap = noMipmap;
  64656. _this.hasAlpha = false;
  64657. _this._format = format;
  64658. _this.isCube = true;
  64659. _this._textureMatrix = BABYLON.Matrix.Identity();
  64660. _this._createPolynomials = createPolynomials;
  64661. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  64662. if (!rootUrl && !files) {
  64663. return _this;
  64664. }
  64665. var lastDot = rootUrl.lastIndexOf(".");
  64666. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  64667. var isDDS = (extension === ".dds");
  64668. var isEnv = (extension === ".env");
  64669. if (isEnv) {
  64670. _this.gammaSpace = false;
  64671. _this._prefiltered = false;
  64672. }
  64673. else {
  64674. _this._prefiltered = prefiltered;
  64675. if (prefiltered) {
  64676. _this.gammaSpace = false;
  64677. }
  64678. }
  64679. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  64680. if (!files) {
  64681. if (!isEnv && !isDDS && !extensions) {
  64682. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  64683. }
  64684. files = [];
  64685. if (extensions) {
  64686. for (var index = 0; index < extensions.length; index++) {
  64687. files.push(rootUrl + extensions[index]);
  64688. }
  64689. }
  64690. }
  64691. _this._files = files;
  64692. if (!_this._texture) {
  64693. if (!scene.useDelayedTextureLoading) {
  64694. if (prefiltered) {
  64695. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  64696. }
  64697. else {
  64698. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  64699. }
  64700. }
  64701. else {
  64702. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  64703. }
  64704. }
  64705. else if (onLoad) {
  64706. if (_this._texture.isReady) {
  64707. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  64708. }
  64709. else {
  64710. _this._texture.onLoadedObservable.add(onLoad);
  64711. }
  64712. }
  64713. return _this;
  64714. }
  64715. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  64716. get: function () {
  64717. return this._boundingBoxSize;
  64718. },
  64719. /**
  64720. * Gets or sets the size of the bounding box associated with the cube texture
  64721. * When defined, the cubemap will switch to local mode
  64722. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64723. * @example https://www.babylonjs-playground.com/#RNASML
  64724. */
  64725. set: function (value) {
  64726. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64727. return;
  64728. }
  64729. this._boundingBoxSize = value;
  64730. var scene = this.getScene();
  64731. if (scene) {
  64732. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64733. }
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  64739. /**
  64740. * Gets texture matrix rotation angle around Y axis radians.
  64741. */
  64742. get: function () {
  64743. return this._rotationY;
  64744. },
  64745. /**
  64746. * Sets texture matrix rotation angle around Y axis in radians.
  64747. */
  64748. set: function (value) {
  64749. this._rotationY = value;
  64750. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  64751. },
  64752. enumerable: true,
  64753. configurable: true
  64754. });
  64755. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  64756. var rootUrlKey = "";
  64757. files.forEach(function (url) { return rootUrlKey += url; });
  64758. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  64759. };
  64760. /**
  64761. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  64762. * @param url defines the url of the prefiltered texture
  64763. * @param scene defines the scene the texture is attached to
  64764. * @param forcedExtension defines the extension of the file if different from the url
  64765. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  64766. * @return the prefiltered texture
  64767. */
  64768. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  64769. if (forcedExtension === void 0) { forcedExtension = null; }
  64770. if (createPolynomials === void 0) { createPolynomials = true; }
  64771. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  64772. };
  64773. // Methods
  64774. CubeTexture.prototype.delayLoad = function () {
  64775. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  64776. return;
  64777. }
  64778. var scene = this.getScene();
  64779. if (!scene) {
  64780. return;
  64781. }
  64782. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  64783. this._texture = this._getFromCache(this.url, this._noMipmap);
  64784. if (!this._texture) {
  64785. if (this._prefiltered) {
  64786. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  64787. }
  64788. else {
  64789. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  64790. }
  64791. }
  64792. };
  64793. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  64794. return this._textureMatrix;
  64795. };
  64796. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  64797. this._textureMatrix = value;
  64798. };
  64799. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  64800. var texture = BABYLON.SerializationHelper.Parse(function () {
  64801. var prefiltered = false;
  64802. if (parsedTexture.prefiltered) {
  64803. prefiltered = parsedTexture.prefiltered;
  64804. }
  64805. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  64806. }, parsedTexture, scene);
  64807. // Local Cubemaps
  64808. if (parsedTexture.boundingBoxPosition) {
  64809. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  64810. }
  64811. if (parsedTexture.boundingBoxSize) {
  64812. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  64813. }
  64814. // Animations
  64815. if (parsedTexture.animations) {
  64816. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  64817. var parsedAnimation = parsedTexture.animations[animationIndex];
  64818. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  64819. }
  64820. }
  64821. return texture;
  64822. };
  64823. CubeTexture.prototype.clone = function () {
  64824. var _this = this;
  64825. return BABYLON.SerializationHelper.Clone(function () {
  64826. var scene = _this.getScene();
  64827. if (!scene) {
  64828. return _this;
  64829. }
  64830. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  64831. }, this);
  64832. };
  64833. __decorate([
  64834. BABYLON.serialize("rotationY")
  64835. ], CubeTexture.prototype, "_rotationY", void 0);
  64836. return CubeTexture;
  64837. }(BABYLON.BaseTexture));
  64838. BABYLON.CubeTexture = CubeTexture;
  64839. })(BABYLON || (BABYLON = {}));
  64840. //# sourceMappingURL=babylon.cubeTexture.js.map
  64841. var BABYLON;
  64842. (function (BABYLON) {
  64843. /**
  64844. * Raw cube texture where the raw buffers are passed in
  64845. */
  64846. var RawCubeTexture = /** @class */ (function (_super) {
  64847. __extends(RawCubeTexture, _super);
  64848. /**
  64849. * Creates a cube texture where the raw buffers are passed in.
  64850. * @param scene defines the scene the texture is attached to
  64851. * @param data defines the array of data to use to create each face
  64852. * @param size defines the size of the textures
  64853. * @param format defines the format of the data
  64854. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  64855. * @param generateMipMaps defines if the engine should generate the mip levels
  64856. * @param invertY defines if data must be stored with Y axis inverted
  64857. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  64858. * @param compression defines the compression used (null by default)
  64859. */
  64860. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  64861. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64862. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64863. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64864. if (invertY === void 0) { invertY = false; }
  64865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64866. if (compression === void 0) { compression = null; }
  64867. var _this = _super.call(this, "", scene) || this;
  64868. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  64869. return _this;
  64870. }
  64871. /**
  64872. * Updates the raw cube texture.
  64873. * @param data defines the data to store
  64874. * @param format defines the data format
  64875. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  64876. * @param invertY defines if data must be stored with Y axis inverted
  64877. * @param compression defines the compression used (null by default)
  64878. * @param level defines which level of the texture to update
  64879. */
  64880. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  64881. if (compression === void 0) { compression = null; }
  64882. if (level === void 0) { level = 0; }
  64883. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  64884. };
  64885. /**
  64886. * Updates a raw cube texture with RGBD encoded data.
  64887. * @param data defines the array of data [mipmap][face] to use to create each face
  64888. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  64889. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  64890. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  64891. * @returns a promsie that resolves when the operation is complete
  64892. */
  64893. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  64894. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  64895. if (lodScale === void 0) { lodScale = 0.8; }
  64896. if (lodOffset === void 0) { lodOffset = 0; }
  64897. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  64898. };
  64899. /**
  64900. * Clones the raw cube texture.
  64901. * @return a new cube texture
  64902. */
  64903. RawCubeTexture.prototype.clone = function () {
  64904. var _this = this;
  64905. return BABYLON.SerializationHelper.Clone(function () {
  64906. var scene = _this.getScene();
  64907. var internalTexture = _this._texture;
  64908. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  64909. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  64910. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  64911. }
  64912. return texture;
  64913. }, this);
  64914. };
  64915. /** @hidden */
  64916. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  64917. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  64918. internalTexture._bufferViewArrayArray = data;
  64919. internalTexture._lodGenerationScale = lodScale;
  64920. internalTexture._lodGenerationOffset = lodOffset;
  64921. internalTexture._sphericalPolynomial = sphericalPolynomial;
  64922. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  64923. internalTexture.isReady = true;
  64924. });
  64925. };
  64926. return RawCubeTexture;
  64927. }(BABYLON.CubeTexture));
  64928. BABYLON.RawCubeTexture = RawCubeTexture;
  64929. })(BABYLON || (BABYLON = {}));
  64930. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  64931. var BABYLON;
  64932. (function (BABYLON) {
  64933. var RenderTargetTexture = /** @class */ (function (_super) {
  64934. __extends(RenderTargetTexture, _super);
  64935. /**
  64936. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  64937. * or used a shadow, depth texture...
  64938. * @param name The friendly name of the texture
  64939. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  64940. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  64941. * @param generateMipMaps True if mip maps need to be generated after render.
  64942. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  64943. * @param type The type of the buffer in the RTT (int, half float, float...)
  64944. * @param isCube True if a cube texture needs to be created
  64945. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  64946. * @param generateDepthBuffer True to generate a depth buffer
  64947. * @param generateStencilBuffer True to generate a stencil buffer
  64948. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  64949. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  64950. */
  64951. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  64952. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  64953. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64954. if (isCube === void 0) { isCube = false; }
  64955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64956. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64957. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  64958. if (isMulti === void 0) { isMulti = false; }
  64959. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64960. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64961. _this.isCube = isCube;
  64962. _this.renderParticles = true;
  64963. _this.renderSprites = false;
  64964. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  64965. _this.ignoreCameraViewport = false;
  64966. // Events
  64967. /**
  64968. * An event triggered when the texture is unbind.
  64969. */
  64970. _this.onBeforeBindObservable = new BABYLON.Observable();
  64971. /**
  64972. * An event triggered when the texture is unbind.
  64973. */
  64974. _this.onAfterUnbindObservable = new BABYLON.Observable();
  64975. /**
  64976. * An event triggered before rendering the texture
  64977. */
  64978. _this.onBeforeRenderObservable = new BABYLON.Observable();
  64979. /**
  64980. * An event triggered after rendering the texture
  64981. */
  64982. _this.onAfterRenderObservable = new BABYLON.Observable();
  64983. /**
  64984. * An event triggered after the texture clear
  64985. */
  64986. _this.onClearObservable = new BABYLON.Observable();
  64987. _this._currentRefreshId = -1;
  64988. _this._refreshRate = 1;
  64989. _this._samples = 1;
  64990. /**
  64991. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  64992. * It must define where the camera used to render the texture is set
  64993. */
  64994. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  64995. scene = _this.getScene();
  64996. if (!scene) {
  64997. return _this;
  64998. }
  64999. _this.renderList = new Array();
  65000. _this._engine = scene.getEngine();
  65001. _this.name = name;
  65002. _this.isRenderTarget = true;
  65003. _this._initialSizeParameter = size;
  65004. _this._processSizeParameter(size);
  65005. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  65006. });
  65007. _this._generateMipMaps = generateMipMaps ? true : false;
  65008. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  65009. // Rendering groups
  65010. _this._renderingManager = new BABYLON.RenderingManager(scene);
  65011. _this._renderingManager._useSceneAutoClearSetup = true;
  65012. if (isMulti) {
  65013. return _this;
  65014. }
  65015. _this._renderTargetOptions = {
  65016. generateMipMaps: generateMipMaps,
  65017. type: type,
  65018. format: format,
  65019. samplingMode: samplingMode,
  65020. generateDepthBuffer: generateDepthBuffer,
  65021. generateStencilBuffer: generateStencilBuffer
  65022. };
  65023. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  65024. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65025. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65026. }
  65027. if (isCube) {
  65028. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  65029. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  65030. _this._textureMatrix = BABYLON.Matrix.Identity();
  65031. }
  65032. else {
  65033. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  65034. }
  65035. return _this;
  65036. }
  65037. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  65038. get: function () {
  65039. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  65040. },
  65041. enumerable: true,
  65042. configurable: true
  65043. });
  65044. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  65045. get: function () {
  65046. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  65047. },
  65048. enumerable: true,
  65049. configurable: true
  65050. });
  65051. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  65052. get: function () {
  65053. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  65054. },
  65055. enumerable: true,
  65056. configurable: true
  65057. });
  65058. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  65059. /**
  65060. * Use this list to define the list of mesh you want to render.
  65061. */
  65062. get: function () {
  65063. return this._renderList;
  65064. },
  65065. set: function (value) {
  65066. this._renderList = value;
  65067. if (this._renderList) {
  65068. this._hookArray(this._renderList);
  65069. }
  65070. },
  65071. enumerable: true,
  65072. configurable: true
  65073. });
  65074. RenderTargetTexture.prototype._hookArray = function (array) {
  65075. var _this = this;
  65076. var oldPush = array.push;
  65077. array.push = function () {
  65078. var items = [];
  65079. for (var _i = 0; _i < arguments.length; _i++) {
  65080. items[_i] = arguments[_i];
  65081. }
  65082. var result = oldPush.apply(array, items);
  65083. _this.getScene().meshes.forEach(function (mesh) {
  65084. mesh._markSubMeshesAsLightDirty();
  65085. });
  65086. return result;
  65087. };
  65088. var oldSplice = array.splice;
  65089. array.splice = function (index, deleteCount) {
  65090. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65091. _this.getScene().meshes.forEach(function (mesh) {
  65092. mesh._markSubMeshesAsLightDirty();
  65093. });
  65094. return deleted;
  65095. };
  65096. };
  65097. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  65098. set: function (callback) {
  65099. if (this._onAfterUnbindObserver) {
  65100. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  65101. }
  65102. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  65103. },
  65104. enumerable: true,
  65105. configurable: true
  65106. });
  65107. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  65108. set: function (callback) {
  65109. if (this._onBeforeRenderObserver) {
  65110. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65111. }
  65112. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65113. },
  65114. enumerable: true,
  65115. configurable: true
  65116. });
  65117. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  65118. set: function (callback) {
  65119. if (this._onAfterRenderObserver) {
  65120. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65121. }
  65122. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65123. },
  65124. enumerable: true,
  65125. configurable: true
  65126. });
  65127. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  65128. set: function (callback) {
  65129. if (this._onClearObserver) {
  65130. this.onClearObservable.remove(this._onClearObserver);
  65131. }
  65132. this._onClearObserver = this.onClearObservable.add(callback);
  65133. },
  65134. enumerable: true,
  65135. configurable: true
  65136. });
  65137. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  65138. get: function () {
  65139. return this._renderTargetOptions;
  65140. },
  65141. enumerable: true,
  65142. configurable: true
  65143. });
  65144. RenderTargetTexture.prototype._onRatioRescale = function () {
  65145. if (this._sizeRatio) {
  65146. this.resize(this._initialSizeParameter);
  65147. }
  65148. };
  65149. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  65150. get: function () {
  65151. return this._boundingBoxSize;
  65152. },
  65153. /**
  65154. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  65155. * When defined, the cubemap will switch to local mode
  65156. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65157. * @example https://www.babylonjs-playground.com/#RNASML
  65158. */
  65159. set: function (value) {
  65160. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65161. return;
  65162. }
  65163. this._boundingBoxSize = value;
  65164. var scene = this.getScene();
  65165. if (scene) {
  65166. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65167. }
  65168. },
  65169. enumerable: true,
  65170. configurable: true
  65171. });
  65172. /**
  65173. * Creates a depth stencil texture.
  65174. * This is only available in WebGL 2 or with the depth texture extension available.
  65175. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  65176. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  65177. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  65178. */
  65179. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  65180. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  65181. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  65182. if (generateStencil === void 0) { generateStencil = false; }
  65183. if (!this.getScene()) {
  65184. return;
  65185. }
  65186. var engine = this.getScene().getEngine();
  65187. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  65188. bilinearFiltering: bilinearFiltering,
  65189. comparisonFunction: comparisonFunction,
  65190. generateStencil: generateStencil,
  65191. isCube: this.isCube
  65192. });
  65193. engine.setFrameBufferDepthStencilTexture(this);
  65194. };
  65195. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  65196. if (size.ratio) {
  65197. this._sizeRatio = size.ratio;
  65198. this._size = {
  65199. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  65200. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  65201. };
  65202. }
  65203. else {
  65204. this._size = size;
  65205. }
  65206. };
  65207. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  65208. get: function () {
  65209. return this._samples;
  65210. },
  65211. set: function (value) {
  65212. if (this._samples === value) {
  65213. return;
  65214. }
  65215. var scene = this.getScene();
  65216. if (!scene) {
  65217. return;
  65218. }
  65219. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  65220. },
  65221. enumerable: true,
  65222. configurable: true
  65223. });
  65224. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  65225. this._currentRefreshId = -1;
  65226. };
  65227. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  65228. get: function () {
  65229. return this._refreshRate;
  65230. },
  65231. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65232. set: function (value) {
  65233. this._refreshRate = value;
  65234. this.resetRefreshCounter();
  65235. },
  65236. enumerable: true,
  65237. configurable: true
  65238. });
  65239. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  65240. if (!this._postProcessManager) {
  65241. var scene = this.getScene();
  65242. if (!scene) {
  65243. return;
  65244. }
  65245. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  65246. this._postProcesses = new Array();
  65247. }
  65248. this._postProcesses.push(postProcess);
  65249. this._postProcesses[0].autoClear = false;
  65250. };
  65251. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  65252. if (!this._postProcesses) {
  65253. return;
  65254. }
  65255. if (dispose) {
  65256. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  65257. var postProcess = _a[_i];
  65258. postProcess.dispose();
  65259. }
  65260. }
  65261. this._postProcesses = [];
  65262. };
  65263. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  65264. if (!this._postProcesses) {
  65265. return;
  65266. }
  65267. var index = this._postProcesses.indexOf(postProcess);
  65268. if (index === -1) {
  65269. return;
  65270. }
  65271. this._postProcesses.splice(index, 1);
  65272. if (this._postProcesses.length > 0) {
  65273. this._postProcesses[0].autoClear = false;
  65274. }
  65275. };
  65276. RenderTargetTexture.prototype._shouldRender = function () {
  65277. if (this._currentRefreshId === -1) { // At least render once
  65278. this._currentRefreshId = 1;
  65279. return true;
  65280. }
  65281. if (this.refreshRate === this._currentRefreshId) {
  65282. this._currentRefreshId = 1;
  65283. return true;
  65284. }
  65285. this._currentRefreshId++;
  65286. return false;
  65287. };
  65288. RenderTargetTexture.prototype.getRenderSize = function () {
  65289. if (this._size.width) {
  65290. return this._size.width;
  65291. }
  65292. return this._size;
  65293. };
  65294. RenderTargetTexture.prototype.getRenderWidth = function () {
  65295. if (this._size.width) {
  65296. return this._size.width;
  65297. }
  65298. return this._size;
  65299. };
  65300. RenderTargetTexture.prototype.getRenderHeight = function () {
  65301. if (this._size.width) {
  65302. return this._size.height;
  65303. }
  65304. return this._size;
  65305. };
  65306. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  65307. get: function () {
  65308. return true;
  65309. },
  65310. enumerable: true,
  65311. configurable: true
  65312. });
  65313. RenderTargetTexture.prototype.scale = function (ratio) {
  65314. var newSize = this.getRenderSize() * ratio;
  65315. this.resize(newSize);
  65316. };
  65317. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  65318. if (this.isCube) {
  65319. return this._textureMatrix;
  65320. }
  65321. return _super.prototype.getReflectionTextureMatrix.call(this);
  65322. };
  65323. RenderTargetTexture.prototype.resize = function (size) {
  65324. this.releaseInternalTexture();
  65325. var scene = this.getScene();
  65326. if (!scene) {
  65327. return;
  65328. }
  65329. this._processSizeParameter(size);
  65330. if (this.isCube) {
  65331. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  65332. }
  65333. else {
  65334. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  65335. }
  65336. };
  65337. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  65338. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  65339. if (dumpForDebug === void 0) { dumpForDebug = false; }
  65340. var scene = this.getScene();
  65341. if (!scene) {
  65342. return;
  65343. }
  65344. var engine = scene.getEngine();
  65345. if (this.useCameraPostProcesses !== undefined) {
  65346. useCameraPostProcess = this.useCameraPostProcesses;
  65347. }
  65348. if (this._waitingRenderList) {
  65349. this.renderList = [];
  65350. for (var index = 0; index < this._waitingRenderList.length; index++) {
  65351. var id = this._waitingRenderList[index];
  65352. var mesh_1 = scene.getMeshByID(id);
  65353. if (mesh_1) {
  65354. this.renderList.push(mesh_1);
  65355. }
  65356. }
  65357. delete this._waitingRenderList;
  65358. }
  65359. // Is predicate defined?
  65360. if (this.renderListPredicate) {
  65361. if (this.renderList) {
  65362. this.renderList.splice(0); // Clear previous renderList
  65363. }
  65364. else {
  65365. this.renderList = [];
  65366. }
  65367. var scene = this.getScene();
  65368. if (!scene) {
  65369. return;
  65370. }
  65371. var sceneMeshes = scene.meshes;
  65372. for (var index = 0; index < sceneMeshes.length; index++) {
  65373. var mesh = sceneMeshes[index];
  65374. if (this.renderListPredicate(mesh)) {
  65375. this.renderList.push(mesh);
  65376. }
  65377. }
  65378. }
  65379. this.onBeforeBindObservable.notifyObservers(this);
  65380. // Set custom projection.
  65381. // Needs to be before binding to prevent changing the aspect ratio.
  65382. var camera;
  65383. if (this.activeCamera) {
  65384. camera = this.activeCamera;
  65385. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65386. if (this.activeCamera !== scene.activeCamera) {
  65387. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  65388. }
  65389. }
  65390. else {
  65391. camera = scene.activeCamera;
  65392. if (camera) {
  65393. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  65394. }
  65395. }
  65396. // Prepare renderingManager
  65397. this._renderingManager.reset();
  65398. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  65399. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  65400. var sceneRenderId = scene.getRenderId();
  65401. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  65402. var mesh = currentRenderList[meshIndex];
  65403. if (mesh) {
  65404. if (!mesh.isReady(this.refreshRate === 0)) {
  65405. this.resetRefreshCounter();
  65406. continue;
  65407. }
  65408. mesh._preActivateForIntermediateRendering(sceneRenderId);
  65409. var isMasked = void 0;
  65410. if (!this.renderList && camera) {
  65411. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  65412. }
  65413. else {
  65414. isMasked = false;
  65415. }
  65416. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  65417. mesh._activate(sceneRenderId);
  65418. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  65419. var subMesh = mesh.subMeshes[subIndex];
  65420. scene._activeIndices.addCount(subMesh.indexCount, false);
  65421. this._renderingManager.dispatch(subMesh, mesh);
  65422. }
  65423. }
  65424. }
  65425. }
  65426. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  65427. var particleSystem = scene.particleSystems[particleIndex];
  65428. var emitter = particleSystem.emitter;
  65429. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  65430. continue;
  65431. }
  65432. if (currentRenderList.indexOf(emitter) >= 0) {
  65433. this._renderingManager.dispatchParticles(particleSystem);
  65434. }
  65435. }
  65436. if (this.isCube) {
  65437. for (var face = 0; face < 6; face++) {
  65438. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65439. scene.incrementRenderId();
  65440. scene.resetCachedMaterial();
  65441. }
  65442. }
  65443. else {
  65444. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  65445. }
  65446. this.onAfterUnbindObservable.notifyObservers(this);
  65447. if (scene.activeCamera) {
  65448. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  65449. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  65450. }
  65451. engine.setViewport(scene.activeCamera.viewport);
  65452. }
  65453. scene.resetCachedMaterial();
  65454. };
  65455. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  65456. var minimum = 128;
  65457. var x = renderDimension * scale;
  65458. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  65459. // Ensure we don't exceed the render dimension (while staying POT)
  65460. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  65461. };
  65462. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65463. var _this = this;
  65464. if (!this._texture) {
  65465. return;
  65466. }
  65467. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  65468. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65469. });
  65470. };
  65471. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  65472. var scene = this.getScene();
  65473. if (!scene) {
  65474. return;
  65475. }
  65476. var engine = scene.getEngine();
  65477. if (!this._texture) {
  65478. return;
  65479. }
  65480. // Bind
  65481. if (this._postProcessManager) {
  65482. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  65483. }
  65484. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  65485. if (this._texture) {
  65486. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  65487. }
  65488. }
  65489. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  65490. // Clear
  65491. if (this.onClearObservable.hasObservers()) {
  65492. this.onClearObservable.notifyObservers(engine);
  65493. }
  65494. else {
  65495. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  65496. }
  65497. if (!this._doNotChangeAspectRatio) {
  65498. scene.updateTransformMatrix(true);
  65499. }
  65500. // Render
  65501. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  65502. if (this._postProcessManager) {
  65503. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  65504. }
  65505. else if (useCameraPostProcess) {
  65506. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  65507. }
  65508. if (!this._doNotChangeAspectRatio) {
  65509. scene.updateTransformMatrix(true);
  65510. }
  65511. // Dump ?
  65512. if (dumpForDebug) {
  65513. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  65514. }
  65515. // Unbind
  65516. if (!this.isCube || faceIndex === 5) {
  65517. if (this.isCube) {
  65518. if (faceIndex === 5) {
  65519. engine.generateMipMapsForCubemap(this._texture);
  65520. }
  65521. }
  65522. this.unbindFrameBuffer(engine, faceIndex);
  65523. }
  65524. else {
  65525. this.onAfterRenderObservable.notifyObservers(faceIndex);
  65526. }
  65527. };
  65528. /**
  65529. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  65530. * This allowed control for front to back rendering or reversly depending of the special needs.
  65531. *
  65532. * @param renderingGroupId The rendering group id corresponding to its index
  65533. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  65534. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  65535. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  65536. */
  65537. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  65538. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  65539. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  65540. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  65541. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  65542. };
  65543. /**
  65544. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  65545. *
  65546. * @param renderingGroupId The rendering group id corresponding to its index
  65547. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  65548. */
  65549. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  65550. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  65551. this._renderingManager._useSceneAutoClearSetup = false;
  65552. };
  65553. RenderTargetTexture.prototype.clone = function () {
  65554. var textureSize = this.getSize();
  65555. 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);
  65556. // Base texture
  65557. newTexture.hasAlpha = this.hasAlpha;
  65558. newTexture.level = this.level;
  65559. // RenderTarget Texture
  65560. newTexture.coordinatesMode = this.coordinatesMode;
  65561. if (this.renderList) {
  65562. newTexture.renderList = this.renderList.slice(0);
  65563. }
  65564. return newTexture;
  65565. };
  65566. RenderTargetTexture.prototype.serialize = function () {
  65567. if (!this.name) {
  65568. return null;
  65569. }
  65570. var serializationObject = _super.prototype.serialize.call(this);
  65571. serializationObject.renderTargetSize = this.getRenderSize();
  65572. serializationObject.renderList = [];
  65573. if (this.renderList) {
  65574. for (var index = 0; index < this.renderList.length; index++) {
  65575. serializationObject.renderList.push(this.renderList[index].id);
  65576. }
  65577. }
  65578. return serializationObject;
  65579. };
  65580. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  65581. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  65582. var objBuffer = this.getInternalTexture();
  65583. var scene = this.getScene();
  65584. if (objBuffer && scene) {
  65585. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  65586. }
  65587. };
  65588. RenderTargetTexture.prototype.dispose = function () {
  65589. if (this._postProcessManager) {
  65590. this._postProcessManager.dispose();
  65591. this._postProcessManager = null;
  65592. }
  65593. this.clearPostProcesses(true);
  65594. if (this._resizeObserver) {
  65595. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  65596. this._resizeObserver = null;
  65597. }
  65598. this.renderList = null;
  65599. // Remove from custom render targets
  65600. var scene = this.getScene();
  65601. if (!scene) {
  65602. return;
  65603. }
  65604. var index = scene.customRenderTargets.indexOf(this);
  65605. if (index >= 0) {
  65606. scene.customRenderTargets.splice(index, 1);
  65607. }
  65608. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  65609. var camera = _a[_i];
  65610. index = camera.customRenderTargets.indexOf(this);
  65611. if (index >= 0) {
  65612. camera.customRenderTargets.splice(index, 1);
  65613. }
  65614. }
  65615. _super.prototype.dispose.call(this);
  65616. };
  65617. RenderTargetTexture.prototype._rebuild = function () {
  65618. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65619. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65620. }
  65621. if (this._postProcessManager) {
  65622. this._postProcessManager._rebuild();
  65623. }
  65624. };
  65625. /**
  65626. * Clear the info related to rendering groups preventing retention point in material dispose.
  65627. */
  65628. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  65629. if (this._renderingManager) {
  65630. this._renderingManager.freeRenderingGroups();
  65631. }
  65632. };
  65633. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  65634. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  65635. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  65636. return RenderTargetTexture;
  65637. }(BABYLON.Texture));
  65638. BABYLON.RenderTargetTexture = RenderTargetTexture;
  65639. })(BABYLON || (BABYLON = {}));
  65640. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  65641. var BABYLON;
  65642. (function (BABYLON) {
  65643. ;
  65644. var MultiRenderTarget = /** @class */ (function (_super) {
  65645. __extends(MultiRenderTarget, _super);
  65646. function MultiRenderTarget(name, size, count, scene, options) {
  65647. var _this = this;
  65648. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  65649. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  65650. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  65651. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  65652. _this._engine = scene.getEngine();
  65653. if (!_this.isSupported) {
  65654. _this.dispose();
  65655. return;
  65656. }
  65657. var types = [];
  65658. var samplingModes = [];
  65659. for (var i = 0; i < count; i++) {
  65660. if (options && options.types && options.types[i] !== undefined) {
  65661. types.push(options.types[i]);
  65662. }
  65663. else {
  65664. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  65665. }
  65666. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  65667. samplingModes.push(options.samplingModes[i]);
  65668. }
  65669. else {
  65670. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65671. }
  65672. }
  65673. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  65674. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  65675. _this._size = size;
  65676. _this._multiRenderTargetOptions = {
  65677. samplingModes: samplingModes,
  65678. generateMipMaps: generateMipMaps,
  65679. generateDepthBuffer: generateDepthBuffer,
  65680. generateStencilBuffer: generateStencilBuffer,
  65681. generateDepthTexture: generateDepthTexture,
  65682. types: types,
  65683. textureCount: count
  65684. };
  65685. _this._createInternalTextures();
  65686. _this._createTextures();
  65687. return _this;
  65688. }
  65689. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  65690. get: function () {
  65691. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  65692. },
  65693. enumerable: true,
  65694. configurable: true
  65695. });
  65696. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  65697. get: function () {
  65698. return this._textures;
  65699. },
  65700. enumerable: true,
  65701. configurable: true
  65702. });
  65703. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  65704. get: function () {
  65705. return this._textures[this._textures.length - 1];
  65706. },
  65707. enumerable: true,
  65708. configurable: true
  65709. });
  65710. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  65711. set: function (wrap) {
  65712. if (this._textures) {
  65713. for (var i = 0; i < this._textures.length; i++) {
  65714. this._textures[i].wrapU = wrap;
  65715. }
  65716. }
  65717. },
  65718. enumerable: true,
  65719. configurable: true
  65720. });
  65721. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  65722. set: function (wrap) {
  65723. if (this._textures) {
  65724. for (var i = 0; i < this._textures.length; i++) {
  65725. this._textures[i].wrapV = wrap;
  65726. }
  65727. }
  65728. },
  65729. enumerable: true,
  65730. configurable: true
  65731. });
  65732. MultiRenderTarget.prototype._rebuild = function () {
  65733. this.releaseInternalTextures();
  65734. this._createInternalTextures();
  65735. for (var i = 0; i < this._internalTextures.length; i++) {
  65736. var texture = this._textures[i];
  65737. texture._texture = this._internalTextures[i];
  65738. }
  65739. // Keeps references to frame buffer and stencil/depth buffer
  65740. this._texture = this._internalTextures[0];
  65741. };
  65742. MultiRenderTarget.prototype._createInternalTextures = function () {
  65743. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  65744. };
  65745. MultiRenderTarget.prototype._createTextures = function () {
  65746. this._textures = [];
  65747. for (var i = 0; i < this._internalTextures.length; i++) {
  65748. var texture = new BABYLON.Texture(null, this.getScene());
  65749. texture._texture = this._internalTextures[i];
  65750. this._textures.push(texture);
  65751. }
  65752. // Keeps references to frame buffer and stencil/depth buffer
  65753. this._texture = this._internalTextures[0];
  65754. };
  65755. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  65756. get: function () {
  65757. return this._samples;
  65758. },
  65759. set: function (value) {
  65760. if (this._samples === value) {
  65761. return;
  65762. }
  65763. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  65764. },
  65765. enumerable: true,
  65766. configurable: true
  65767. });
  65768. MultiRenderTarget.prototype.resize = function (size) {
  65769. this.releaseInternalTextures();
  65770. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  65771. this._createInternalTextures();
  65772. };
  65773. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  65774. var _this = this;
  65775. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  65776. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  65777. });
  65778. };
  65779. MultiRenderTarget.prototype.dispose = function () {
  65780. this.releaseInternalTextures();
  65781. _super.prototype.dispose.call(this);
  65782. };
  65783. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  65784. if (!this._internalTextures) {
  65785. return;
  65786. }
  65787. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  65788. if (this._internalTextures[i] !== undefined) {
  65789. this._internalTextures[i].dispose();
  65790. this._internalTextures.splice(i, 1);
  65791. }
  65792. }
  65793. };
  65794. return MultiRenderTarget;
  65795. }(BABYLON.RenderTargetTexture));
  65796. BABYLON.MultiRenderTarget = MultiRenderTarget;
  65797. })(BABYLON || (BABYLON = {}));
  65798. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  65799. var BABYLON;
  65800. (function (BABYLON) {
  65801. var MirrorTexture = /** @class */ (function (_super) {
  65802. __extends(MirrorTexture, _super);
  65803. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  65804. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65806. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  65807. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  65808. _this.scene = scene;
  65809. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  65810. _this._transformMatrix = BABYLON.Matrix.Zero();
  65811. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  65812. _this._adaptiveBlurKernel = 0;
  65813. _this._blurKernelX = 0;
  65814. _this._blurKernelY = 0;
  65815. _this._blurRatio = 1.0;
  65816. _this.ignoreCameraViewport = true;
  65817. _this._updateGammaSpace();
  65818. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  65819. _this._updateGammaSpace;
  65820. });
  65821. _this.onBeforeRenderObservable.add(function () {
  65822. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  65823. _this._savedViewMatrix = scene.getViewMatrix();
  65824. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  65825. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  65826. scene.clipPlane = _this.mirrorPlane;
  65827. scene.getEngine().cullBackFaces = false;
  65828. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  65829. });
  65830. _this.onAfterRenderObservable.add(function () {
  65831. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  65832. scene.getEngine().cullBackFaces = true;
  65833. scene._mirroredCameraPosition = null;
  65834. delete scene.clipPlane;
  65835. });
  65836. return _this;
  65837. }
  65838. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  65839. get: function () {
  65840. return this._blurRatio;
  65841. },
  65842. set: function (value) {
  65843. if (this._blurRatio === value) {
  65844. return;
  65845. }
  65846. this._blurRatio = value;
  65847. this._preparePostProcesses();
  65848. },
  65849. enumerable: true,
  65850. configurable: true
  65851. });
  65852. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  65853. set: function (value) {
  65854. this._adaptiveBlurKernel = value;
  65855. this._autoComputeBlurKernel();
  65856. },
  65857. enumerable: true,
  65858. configurable: true
  65859. });
  65860. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  65861. set: function (value) {
  65862. this.blurKernelX = value;
  65863. this.blurKernelY = value;
  65864. },
  65865. enumerable: true,
  65866. configurable: true
  65867. });
  65868. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  65869. get: function () {
  65870. return this._blurKernelX;
  65871. },
  65872. set: function (value) {
  65873. if (this._blurKernelX === value) {
  65874. return;
  65875. }
  65876. this._blurKernelX = value;
  65877. this._preparePostProcesses();
  65878. },
  65879. enumerable: true,
  65880. configurable: true
  65881. });
  65882. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  65883. get: function () {
  65884. return this._blurKernelY;
  65885. },
  65886. set: function (value) {
  65887. if (this._blurKernelY === value) {
  65888. return;
  65889. }
  65890. this._blurKernelY = value;
  65891. this._preparePostProcesses();
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  65897. var engine = this.getScene().getEngine();
  65898. var dw = this.getRenderWidth() / engine.getRenderWidth();
  65899. var dh = this.getRenderHeight() / engine.getRenderHeight();
  65900. this.blurKernelX = this._adaptiveBlurKernel * dw;
  65901. this.blurKernelY = this._adaptiveBlurKernel * dh;
  65902. };
  65903. MirrorTexture.prototype._onRatioRescale = function () {
  65904. if (this._sizeRatio) {
  65905. this.resize(this._initialSizeParameter);
  65906. if (!this._adaptiveBlurKernel) {
  65907. this._preparePostProcesses();
  65908. }
  65909. }
  65910. if (this._adaptiveBlurKernel) {
  65911. this._autoComputeBlurKernel();
  65912. }
  65913. };
  65914. MirrorTexture.prototype._updateGammaSpace = function () {
  65915. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  65916. };
  65917. MirrorTexture.prototype._preparePostProcesses = function () {
  65918. this.clearPostProcesses(true);
  65919. if (this._blurKernelX && this._blurKernelY) {
  65920. var engine = this.getScene().getEngine();
  65921. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65922. 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);
  65923. this._blurX.autoClear = false;
  65924. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  65925. this._blurX.inputTexture = this._texture;
  65926. }
  65927. else {
  65928. this._blurX.alwaysForcePOT = true;
  65929. }
  65930. 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);
  65931. this._blurY.autoClear = false;
  65932. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  65933. this.addPostProcess(this._blurX);
  65934. this.addPostProcess(this._blurY);
  65935. }
  65936. else {
  65937. if (this._blurY) {
  65938. this.removePostProcess(this._blurY);
  65939. this._blurY.dispose();
  65940. this._blurY = null;
  65941. }
  65942. if (this._blurX) {
  65943. this.removePostProcess(this._blurX);
  65944. this._blurX.dispose();
  65945. this._blurX = null;
  65946. }
  65947. }
  65948. };
  65949. MirrorTexture.prototype.clone = function () {
  65950. var scene = this.getScene();
  65951. if (!scene) {
  65952. return this;
  65953. }
  65954. var textureSize = this.getSize();
  65955. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  65956. // Base texture
  65957. newTexture.hasAlpha = this.hasAlpha;
  65958. newTexture.level = this.level;
  65959. // Mirror Texture
  65960. newTexture.mirrorPlane = this.mirrorPlane.clone();
  65961. if (this.renderList) {
  65962. newTexture.renderList = this.renderList.slice(0);
  65963. }
  65964. return newTexture;
  65965. };
  65966. MirrorTexture.prototype.serialize = function () {
  65967. if (!this.name) {
  65968. return null;
  65969. }
  65970. var serializationObject = _super.prototype.serialize.call(this);
  65971. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  65972. return serializationObject;
  65973. };
  65974. MirrorTexture.prototype.dispose = function () {
  65975. _super.prototype.dispose.call(this);
  65976. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  65977. };
  65978. return MirrorTexture;
  65979. }(BABYLON.RenderTargetTexture));
  65980. BABYLON.MirrorTexture = MirrorTexture;
  65981. })(BABYLON || (BABYLON = {}));
  65982. //# sourceMappingURL=babylon.mirrorTexture.js.map
  65983. var BABYLON;
  65984. (function (BABYLON) {
  65985. /**
  65986. * Creates a refraction texture used by refraction channel of the standard material.
  65987. * @param name the texture name
  65988. * @param size size of the underlying texture
  65989. * @param scene root scene
  65990. */
  65991. var RefractionTexture = /** @class */ (function (_super) {
  65992. __extends(RefractionTexture, _super);
  65993. function RefractionTexture(name, size, scene, generateMipMaps) {
  65994. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  65995. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  65996. _this.depth = 2.0;
  65997. _this.onBeforeRenderObservable.add(function () {
  65998. scene.clipPlane = _this.refractionPlane;
  65999. });
  66000. _this.onAfterRenderObservable.add(function () {
  66001. delete scene.clipPlane;
  66002. });
  66003. return _this;
  66004. }
  66005. RefractionTexture.prototype.clone = function () {
  66006. var scene = this.getScene();
  66007. if (!scene) {
  66008. return this;
  66009. }
  66010. var textureSize = this.getSize();
  66011. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  66012. // Base texture
  66013. newTexture.hasAlpha = this.hasAlpha;
  66014. newTexture.level = this.level;
  66015. // Refraction Texture
  66016. newTexture.refractionPlane = this.refractionPlane.clone();
  66017. if (this.renderList) {
  66018. newTexture.renderList = this.renderList.slice(0);
  66019. }
  66020. newTexture.depth = this.depth;
  66021. return newTexture;
  66022. };
  66023. RefractionTexture.prototype.serialize = function () {
  66024. if (!this.name) {
  66025. return null;
  66026. }
  66027. var serializationObject = _super.prototype.serialize.call(this);
  66028. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  66029. serializationObject.depth = this.depth;
  66030. return serializationObject;
  66031. };
  66032. return RefractionTexture;
  66033. }(BABYLON.RenderTargetTexture));
  66034. BABYLON.RefractionTexture = RefractionTexture;
  66035. })(BABYLON || (BABYLON = {}));
  66036. //# sourceMappingURL=babylon.refractionTexture.js.map
  66037. var BABYLON;
  66038. (function (BABYLON) {
  66039. /**
  66040. * A class extending {BABYLON.Texture} allowing drawing on a texture
  66041. * @see http://doc.babylonjs.com/how_to/dynamictexture
  66042. */
  66043. var DynamicTexture = /** @class */ (function (_super) {
  66044. __extends(DynamicTexture, _super);
  66045. /**
  66046. * Creates a {BABYLON.DynamicTexture}
  66047. * @param name defines the name of the texture
  66048. * @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
  66049. * @param scene defines the scene where you want the texture
  66050. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  66051. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  66052. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  66053. */
  66054. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  66055. if (scene === void 0) { scene = null; }
  66056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66057. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66058. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  66059. _this.name = name;
  66060. _this._engine = _this.getScene().getEngine();
  66061. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66062. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66063. _this._generateMipMaps = generateMipMaps;
  66064. if (options.getContext) {
  66065. _this._canvas = options;
  66066. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66067. }
  66068. else {
  66069. _this._canvas = document.createElement("canvas");
  66070. if (options.width || options.width === 0) {
  66071. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  66072. }
  66073. else {
  66074. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  66075. }
  66076. }
  66077. var textureSize = _this.getSize();
  66078. _this._canvas.width = textureSize.width;
  66079. _this._canvas.height = textureSize.height;
  66080. _this._context = _this._canvas.getContext("2d");
  66081. return _this;
  66082. }
  66083. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  66084. /**
  66085. * Gets the current state of canRescale
  66086. */
  66087. get: function () {
  66088. return true;
  66089. },
  66090. enumerable: true,
  66091. configurable: true
  66092. });
  66093. DynamicTexture.prototype._recreate = function (textureSize) {
  66094. this._canvas.width = textureSize.width;
  66095. this._canvas.height = textureSize.height;
  66096. this.releaseInternalTexture();
  66097. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  66098. };
  66099. /**
  66100. * Scales the texture
  66101. * @param ratio the scale factor to apply to both width and height
  66102. */
  66103. DynamicTexture.prototype.scale = function (ratio) {
  66104. var textureSize = this.getSize();
  66105. textureSize.width *= ratio;
  66106. textureSize.height *= ratio;
  66107. this._recreate(textureSize);
  66108. };
  66109. /**
  66110. * Resizes the texture
  66111. * @param width the new width
  66112. * @param height the new height
  66113. */
  66114. DynamicTexture.prototype.scaleTo = function (width, height) {
  66115. var textureSize = this.getSize();
  66116. textureSize.width = width;
  66117. textureSize.height = height;
  66118. this._recreate(textureSize);
  66119. };
  66120. /**
  66121. * Gets the context of the canvas used by the texture
  66122. * @returns the canvas context of the dynamic texture
  66123. */
  66124. DynamicTexture.prototype.getContext = function () {
  66125. return this._context;
  66126. };
  66127. /**
  66128. * Clears the texture
  66129. */
  66130. DynamicTexture.prototype.clear = function () {
  66131. var size = this.getSize();
  66132. this._context.fillRect(0, 0, size.width, size.height);
  66133. };
  66134. /**
  66135. * Updates the texture
  66136. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66137. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  66138. */
  66139. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  66140. if (premulAlpha === void 0) { premulAlpha = false; }
  66141. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  66142. };
  66143. /**
  66144. * Draws text onto the texture
  66145. * @param text defines the text to be drawn
  66146. * @param x defines the placement of the text from the left
  66147. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  66148. * @param font defines the font to be used with font-style, font-size, font-name
  66149. * @param color defines the color used for the text
  66150. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  66151. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  66152. * @param update defines whether texture is immediately update (default is true)
  66153. */
  66154. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  66155. if (update === void 0) { update = true; }
  66156. var size = this.getSize();
  66157. if (clearColor) {
  66158. this._context.fillStyle = clearColor;
  66159. this._context.fillRect(0, 0, size.width, size.height);
  66160. }
  66161. this._context.font = font;
  66162. if (x === null || x === undefined) {
  66163. var textSize = this._context.measureText(text);
  66164. x = (size.width - textSize.width) / 2;
  66165. }
  66166. if (y === null || y === undefined) {
  66167. var fontSize = parseInt((font.replace(/\D/g, '')));
  66168. y = (size.height / 2) + (fontSize / 3.65);
  66169. }
  66170. this._context.fillStyle = color;
  66171. this._context.fillText(text, x, y);
  66172. if (update) {
  66173. this.update(invertY);
  66174. }
  66175. };
  66176. /**
  66177. * Clones the texture
  66178. * @returns the clone of the texture.
  66179. */
  66180. DynamicTexture.prototype.clone = function () {
  66181. var scene = this.getScene();
  66182. if (!scene) {
  66183. return this;
  66184. }
  66185. var textureSize = this.getSize();
  66186. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  66187. // Base texture
  66188. newTexture.hasAlpha = this.hasAlpha;
  66189. newTexture.level = this.level;
  66190. // Dynamic Texture
  66191. newTexture.wrapU = this.wrapU;
  66192. newTexture.wrapV = this.wrapV;
  66193. return newTexture;
  66194. };
  66195. /** @hidden */
  66196. DynamicTexture.prototype._rebuild = function () {
  66197. this.update();
  66198. };
  66199. return DynamicTexture;
  66200. }(BABYLON.Texture));
  66201. BABYLON.DynamicTexture = DynamicTexture;
  66202. })(BABYLON || (BABYLON = {}));
  66203. //# sourceMappingURL=babylon.dynamicTexture.js.map
  66204. var BABYLON;
  66205. (function (BABYLON) {
  66206. var VideoTexture = /** @class */ (function (_super) {
  66207. __extends(VideoTexture, _super);
  66208. /**
  66209. * Creates a video texture.
  66210. * Sample : https://doc.babylonjs.com/how_to/video_texture
  66211. * @param {string | null} name optional name, will detect from video source, if not defined
  66212. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  66213. * @param {BABYLON.Scene} scene is obviously the current scene.
  66214. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  66215. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  66216. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  66217. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  66218. */
  66219. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  66220. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66221. if (invertY === void 0) { invertY = false; }
  66222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66223. if (settings === void 0) { settings = {
  66224. autoPlay: true,
  66225. loop: true,
  66226. autoUpdateTexture: true,
  66227. }; }
  66228. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66229. _this._onUserActionRequestedObservable = null;
  66230. _this._stillImageCaptured = false;
  66231. _this._poster = false;
  66232. _this._createInternalTexture = function () {
  66233. if (_this._texture != null) {
  66234. if (_this._poster) {
  66235. _this._texture.dispose();
  66236. _this._poster = false;
  66237. }
  66238. else {
  66239. return;
  66240. }
  66241. }
  66242. if (!_this._engine.needPOTTextures ||
  66243. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  66244. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66245. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66246. }
  66247. else {
  66248. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66249. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66250. _this._generateMipMaps = false;
  66251. }
  66252. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  66253. if (!_this.video.autoplay) {
  66254. var oldHandler_1 = _this.video.onplaying;
  66255. var error_1 = false;
  66256. _this.video.onplaying = function () {
  66257. _this.video.onplaying = oldHandler_1;
  66258. _this._texture.isReady = true;
  66259. _this._updateInternalTexture();
  66260. if (!error_1) {
  66261. _this.video.pause();
  66262. }
  66263. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66264. _this.onLoadObservable.notifyObservers(_this);
  66265. }
  66266. };
  66267. var playing = _this.video.play();
  66268. if (playing) {
  66269. playing.then(function () {
  66270. // Everything is good.
  66271. })
  66272. .catch(function () {
  66273. error_1 = true;
  66274. // On Chrome for instance, new policies might prevent playing without user interaction.
  66275. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  66276. _this._onUserActionRequestedObservable.notifyObservers(_this);
  66277. }
  66278. });
  66279. }
  66280. else {
  66281. _this.video.onplaying = oldHandler_1;
  66282. _this._texture.isReady = true;
  66283. _this._updateInternalTexture();
  66284. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66285. _this.onLoadObservable.notifyObservers(_this);
  66286. }
  66287. }
  66288. }
  66289. else {
  66290. _this._texture.isReady = true;
  66291. _this._updateInternalTexture();
  66292. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  66293. _this.onLoadObservable.notifyObservers(_this);
  66294. }
  66295. }
  66296. };
  66297. _this.reset = function () {
  66298. if (_this._texture == null) {
  66299. return;
  66300. }
  66301. if (!_this._poster) {
  66302. _this._texture.dispose();
  66303. _this._texture = null;
  66304. }
  66305. };
  66306. _this._updateInternalTexture = function (e) {
  66307. if (_this._texture == null || !_this._texture.isReady) {
  66308. return;
  66309. }
  66310. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  66311. return;
  66312. }
  66313. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  66314. };
  66315. _this._engine = _this.getScene().getEngine();
  66316. _this._generateMipMaps = generateMipMaps;
  66317. _this._samplingMode = samplingMode;
  66318. _this.autoUpdateTexture = settings.autoUpdateTexture;
  66319. _this.name = name || _this._getName(src);
  66320. _this.video = _this._getVideo(src);
  66321. if (settings.poster) {
  66322. _this.video.poster = settings.poster;
  66323. }
  66324. if (settings.autoPlay !== undefined) {
  66325. _this.video.autoplay = settings.autoPlay;
  66326. }
  66327. if (settings.loop !== undefined) {
  66328. _this.video.loop = settings.loop;
  66329. }
  66330. _this.video.setAttribute("playsinline", "");
  66331. _this.video.addEventListener("canplay", _this._createInternalTexture);
  66332. _this.video.addEventListener("paused", _this._updateInternalTexture);
  66333. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  66334. _this.video.addEventListener("emptied", _this.reset);
  66335. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  66336. _this._createInternalTexture();
  66337. }
  66338. if (settings.poster) {
  66339. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  66340. _this._poster = true;
  66341. }
  66342. return _this;
  66343. }
  66344. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  66345. get: function () {
  66346. if (!this._onUserActionRequestedObservable) {
  66347. this._onUserActionRequestedObservable = new BABYLON.Observable();
  66348. }
  66349. return this._onUserActionRequestedObservable;
  66350. },
  66351. enumerable: true,
  66352. configurable: true
  66353. });
  66354. VideoTexture.prototype._getName = function (src) {
  66355. if (src instanceof HTMLVideoElement) {
  66356. return src.currentSrc;
  66357. }
  66358. if (typeof src === "object") {
  66359. return src.toString();
  66360. }
  66361. return src;
  66362. };
  66363. ;
  66364. VideoTexture.prototype._getVideo = function (src) {
  66365. if (src instanceof HTMLVideoElement) {
  66366. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  66367. return src;
  66368. }
  66369. var video = document.createElement("video");
  66370. if (typeof src === "string") {
  66371. BABYLON.Tools.SetCorsBehavior(src, video);
  66372. video.src = src;
  66373. }
  66374. else {
  66375. BABYLON.Tools.SetCorsBehavior(src[0], video);
  66376. src.forEach(function (url) {
  66377. var source = document.createElement("source");
  66378. source.src = url;
  66379. video.appendChild(source);
  66380. });
  66381. }
  66382. return video;
  66383. };
  66384. ;
  66385. /**
  66386. * Internal method to initiate `update`.
  66387. */
  66388. VideoTexture.prototype._rebuild = function () {
  66389. this.update();
  66390. };
  66391. /**
  66392. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  66393. */
  66394. VideoTexture.prototype.update = function () {
  66395. if (!this.autoUpdateTexture) {
  66396. // Expecting user to call `updateTexture` manually
  66397. return;
  66398. }
  66399. this.updateTexture(true);
  66400. };
  66401. /**
  66402. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  66403. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  66404. */
  66405. VideoTexture.prototype.updateTexture = function (isVisible) {
  66406. if (!isVisible) {
  66407. return;
  66408. }
  66409. if (this.video.paused && this._stillImageCaptured) {
  66410. return;
  66411. }
  66412. this._stillImageCaptured = true;
  66413. this._updateInternalTexture();
  66414. };
  66415. /**
  66416. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  66417. * @param url New url.
  66418. */
  66419. VideoTexture.prototype.updateURL = function (url) {
  66420. this.video.src = url;
  66421. };
  66422. VideoTexture.prototype.dispose = function () {
  66423. _super.prototype.dispose.call(this);
  66424. if (this._onUserActionRequestedObservable) {
  66425. this._onUserActionRequestedObservable.clear();
  66426. this._onUserActionRequestedObservable = null;
  66427. }
  66428. this.video.removeEventListener("canplay", this._createInternalTexture);
  66429. this.video.removeEventListener("paused", this._updateInternalTexture);
  66430. this.video.removeEventListener("seeked", this._updateInternalTexture);
  66431. this.video.removeEventListener("emptied", this.reset);
  66432. this.video.pause();
  66433. };
  66434. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  66435. var video = document.createElement("video");
  66436. video.setAttribute('autoplay', '');
  66437. video.setAttribute('muted', '');
  66438. video.setAttribute('playsinline', '');
  66439. var constraintsDeviceId;
  66440. if (constraints && constraints.deviceId) {
  66441. constraintsDeviceId = {
  66442. exact: constraints.deviceId,
  66443. };
  66444. }
  66445. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  66446. if (navigator.mediaDevices) {
  66447. navigator.mediaDevices.getUserMedia({ video: constraints })
  66448. .then(function (stream) {
  66449. if (video.mozSrcObject !== undefined) {
  66450. // hack for Firefox < 19
  66451. video.mozSrcObject = stream;
  66452. }
  66453. else {
  66454. video.srcObject = stream;
  66455. }
  66456. var onPlaying = function () {
  66457. if (onReady) {
  66458. onReady(new VideoTexture("video", video, scene, true, true));
  66459. }
  66460. video.removeEventListener("playing", onPlaying);
  66461. };
  66462. video.addEventListener("playing", onPlaying);
  66463. video.play();
  66464. })
  66465. .catch(function (err) {
  66466. BABYLON.Tools.Error(err.name);
  66467. });
  66468. }
  66469. else {
  66470. navigator.getUserMedia =
  66471. navigator.getUserMedia ||
  66472. navigator.webkitGetUserMedia ||
  66473. navigator.mozGetUserMedia ||
  66474. navigator.msGetUserMedia;
  66475. if (navigator.getUserMedia) {
  66476. navigator.getUserMedia({
  66477. video: {
  66478. deviceId: constraintsDeviceId,
  66479. width: {
  66480. min: (constraints && constraints.minWidth) || 256,
  66481. max: (constraints && constraints.maxWidth) || 640,
  66482. },
  66483. height: {
  66484. min: (constraints && constraints.minHeight) || 256,
  66485. max: (constraints && constraints.maxHeight) || 480,
  66486. },
  66487. },
  66488. }, function (stream) {
  66489. if (video.mozSrcObject !== undefined) {
  66490. // hack for Firefox < 19
  66491. video.mozSrcObject = stream;
  66492. }
  66493. else {
  66494. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  66495. }
  66496. video.play();
  66497. if (onReady) {
  66498. onReady(new VideoTexture("video", video, scene, true, true));
  66499. }
  66500. }, function (e) {
  66501. BABYLON.Tools.Error(e.name);
  66502. });
  66503. }
  66504. }
  66505. };
  66506. return VideoTexture;
  66507. }(BABYLON.Texture));
  66508. BABYLON.VideoTexture = VideoTexture;
  66509. })(BABYLON || (BABYLON = {}));
  66510. //# sourceMappingURL=babylon.videoTexture.js.map
  66511. var BABYLON;
  66512. (function (BABYLON) {
  66513. var RawTexture = /** @class */ (function (_super) {
  66514. __extends(RawTexture, _super);
  66515. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  66516. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66517. if (invertY === void 0) { invertY = false; }
  66518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66519. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66520. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66521. _this.format = format;
  66522. _this._engine = scene.getEngine();
  66523. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  66524. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66525. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66526. return _this;
  66527. }
  66528. RawTexture.prototype.update = function (data) {
  66529. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66530. };
  66531. // Statics
  66532. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66533. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66534. if (invertY === void 0) { invertY = false; }
  66535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66536. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  66537. };
  66538. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66540. if (invertY === void 0) { invertY = false; }
  66541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66542. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66543. };
  66544. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  66545. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66546. if (invertY === void 0) { invertY = false; }
  66547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66548. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  66549. };
  66550. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66551. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66552. if (invertY === void 0) { invertY = false; }
  66553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66554. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66555. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  66556. };
  66557. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66558. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66559. if (invertY === void 0) { invertY = false; }
  66560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66561. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66562. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  66563. };
  66564. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  66565. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66566. if (invertY === void 0) { invertY = false; }
  66567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66568. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  66569. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  66570. };
  66571. return RawTexture;
  66572. }(BABYLON.Texture));
  66573. BABYLON.RawTexture = RawTexture;
  66574. })(BABYLON || (BABYLON = {}));
  66575. //# sourceMappingURL=babylon.rawTexture.js.map
  66576. var BABYLON;
  66577. (function (BABYLON) {
  66578. /**
  66579. * Class used to store 3D textures containing user data
  66580. */
  66581. var RawTexture3D = /** @class */ (function (_super) {
  66582. __extends(RawTexture3D, _super);
  66583. /**
  66584. * Create a new RawTexture3D
  66585. * @param data defines the data of the texture
  66586. * @param width defines the width of the texture
  66587. * @param height defines the height of the texture
  66588. * @param depth defines the depth of the texture
  66589. * @param format defines the texture format to use
  66590. * @param scene defines the hosting scene
  66591. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  66592. * @param invertY defines if texture must be stored with Y axis inverted
  66593. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  66594. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  66595. */
  66596. function RawTexture3D(data, width, height, depth,
  66597. /** Gets or sets the texture format to use */
  66598. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  66599. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66600. if (invertY === void 0) { invertY = false; }
  66601. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66602. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66603. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  66604. _this.format = format;
  66605. _this._engine = scene.getEngine();
  66606. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  66607. _this.is3D = true;
  66608. return _this;
  66609. }
  66610. /**
  66611. * Update the texture with new data
  66612. * @param data defines the data to store in the texture
  66613. */
  66614. RawTexture3D.prototype.update = function (data) {
  66615. if (!this._texture) {
  66616. return;
  66617. }
  66618. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  66619. };
  66620. return RawTexture3D;
  66621. }(BABYLON.Texture));
  66622. BABYLON.RawTexture3D = RawTexture3D;
  66623. })(BABYLON || (BABYLON = {}));
  66624. //# sourceMappingURL=babylon.rawTexture3D.js.map
  66625. var BABYLON;
  66626. (function (BABYLON) {
  66627. /**
  66628. * PostProcessManager is used to manage one or more post processes or post process pipelines
  66629. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66630. */
  66631. var PostProcessManager = /** @class */ (function () {
  66632. /**
  66633. * Creates a new instance PostProcess
  66634. * @param scene The scene that the post process is associated with.
  66635. */
  66636. function PostProcessManager(scene) {
  66637. this._vertexBuffers = {};
  66638. this._scene = scene;
  66639. }
  66640. PostProcessManager.prototype._prepareBuffers = function () {
  66641. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  66642. return;
  66643. }
  66644. // VBO
  66645. var vertices = [];
  66646. vertices.push(1, 1);
  66647. vertices.push(-1, 1);
  66648. vertices.push(-1, -1);
  66649. vertices.push(1, -1);
  66650. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66651. this._buildIndexBuffer();
  66652. };
  66653. PostProcessManager.prototype._buildIndexBuffer = function () {
  66654. // Indices
  66655. var indices = [];
  66656. indices.push(0);
  66657. indices.push(1);
  66658. indices.push(2);
  66659. indices.push(0);
  66660. indices.push(2);
  66661. indices.push(3);
  66662. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  66663. };
  66664. /**
  66665. * Rebuilds the vertex buffers of the manager.
  66666. */
  66667. PostProcessManager.prototype._rebuild = function () {
  66668. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66669. if (!vb) {
  66670. return;
  66671. }
  66672. vb._rebuild();
  66673. this._buildIndexBuffer();
  66674. };
  66675. // Methods
  66676. /**
  66677. * Prepares a frame to be run through a post process.
  66678. * @param sourceTexture The input texture to the post procesess. (default: null)
  66679. * @param postProcesses An array of post processes to be run. (default: null)
  66680. * @returns True if the post processes were able to be run.
  66681. */
  66682. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  66683. if (sourceTexture === void 0) { sourceTexture = null; }
  66684. if (postProcesses === void 0) { postProcesses = null; }
  66685. var camera = this._scene.activeCamera;
  66686. if (!camera) {
  66687. return false;
  66688. }
  66689. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66690. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66691. return false;
  66692. }
  66693. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  66694. return true;
  66695. };
  66696. /**
  66697. * Manually render a set of post processes to a texture.
  66698. * @param postProcesses An array of post processes to be run.
  66699. * @param targetTexture The target texture to render to.
  66700. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  66701. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  66702. * @param lodLevel defines which lod of the texture to render to
  66703. */
  66704. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  66705. if (targetTexture === void 0) { targetTexture = null; }
  66706. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66707. if (faceIndex === void 0) { faceIndex = 0; }
  66708. if (lodLevel === void 0) { lodLevel = 0; }
  66709. var engine = this._scene.getEngine();
  66710. for (var index = 0; index < postProcesses.length; index++) {
  66711. if (index < postProcesses.length - 1) {
  66712. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  66713. }
  66714. else {
  66715. if (targetTexture) {
  66716. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  66717. }
  66718. else {
  66719. engine.restoreDefaultFramebuffer();
  66720. }
  66721. }
  66722. var pp = postProcesses[index];
  66723. var effect = pp.apply();
  66724. if (effect) {
  66725. pp.onBeforeRenderObservable.notifyObservers(effect);
  66726. // VBOs
  66727. this._prepareBuffers();
  66728. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66729. // Draw order
  66730. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66731. pp.onAfterRenderObservable.notifyObservers(effect);
  66732. }
  66733. }
  66734. // Restore depth buffer
  66735. engine.setDepthBuffer(true);
  66736. engine.setDepthWrite(true);
  66737. };
  66738. /**
  66739. * Finalize the result of the output of the postprocesses.
  66740. * @param doNotPresent If true the result will not be displayed to the screen.
  66741. * @param targetTexture The target texture to render to.
  66742. * @param faceIndex The index of the face to bind the target texture to.
  66743. * @param postProcesses The array of post processes to render.
  66744. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  66745. */
  66746. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  66747. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  66748. var camera = this._scene.activeCamera;
  66749. if (!camera) {
  66750. return;
  66751. }
  66752. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  66753. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  66754. return;
  66755. }
  66756. var engine = this._scene.getEngine();
  66757. for (var index = 0, len = postProcesses.length; index < len; index++) {
  66758. var pp = postProcesses[index];
  66759. if (index < len - 1) {
  66760. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  66761. }
  66762. else {
  66763. if (targetTexture) {
  66764. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  66765. pp._outputTexture = targetTexture;
  66766. }
  66767. else {
  66768. engine.restoreDefaultFramebuffer();
  66769. pp._outputTexture = null;
  66770. }
  66771. }
  66772. if (doNotPresent) {
  66773. break;
  66774. }
  66775. var effect = pp.apply();
  66776. if (effect) {
  66777. pp.onBeforeRenderObservable.notifyObservers(effect);
  66778. // VBOs
  66779. this._prepareBuffers();
  66780. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  66781. // Draw order
  66782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66783. pp.onAfterRenderObservable.notifyObservers(effect);
  66784. }
  66785. }
  66786. // Restore states
  66787. engine.setDepthBuffer(true);
  66788. engine.setDepthWrite(true);
  66789. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66790. };
  66791. /**
  66792. * Disposes of the post process manager.
  66793. */
  66794. PostProcessManager.prototype.dispose = function () {
  66795. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66796. if (buffer) {
  66797. buffer.dispose();
  66798. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66799. }
  66800. if (this._indexBuffer) {
  66801. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  66802. this._indexBuffer = null;
  66803. }
  66804. };
  66805. return PostProcessManager;
  66806. }());
  66807. BABYLON.PostProcessManager = PostProcessManager;
  66808. })(BABYLON || (BABYLON = {}));
  66809. //# sourceMappingURL=babylon.postProcessManager.js.map
  66810. var BABYLON;
  66811. (function (BABYLON) {
  66812. /**
  66813. * PostProcess can be used to apply a shader to a texture after it has been rendered
  66814. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  66815. */
  66816. var PostProcess = /** @class */ (function () {
  66817. /**
  66818. * Creates a new instance PostProcess
  66819. * @param name The name of the PostProcess.
  66820. * @param fragmentUrl The url of the fragment shader to be used.
  66821. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  66822. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  66823. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  66824. * @param camera The camera to apply the render pass to.
  66825. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66826. * @param engine The engine which the post process will be applied. (default: current engine)
  66827. * @param reusable If the post process can be reused on the same frame. (default: false)
  66828. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  66829. * @param textureType Type of textures used when performing the post process. (default: 0)
  66830. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  66831. * @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
  66832. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  66833. */
  66834. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  66835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  66836. if (defines === void 0) { defines = null; }
  66837. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66838. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  66839. if (blockCompilation === void 0) { blockCompilation = false; }
  66840. this.name = name;
  66841. /**
  66842. * Width of the texture to apply the post process on
  66843. */
  66844. this.width = -1;
  66845. /**
  66846. * Height of the texture to apply the post process on
  66847. */
  66848. this.height = -1;
  66849. /**
  66850. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  66851. */
  66852. this._outputTexture = null;
  66853. /**
  66854. * If the buffer needs to be cleared before applying the post process. (default: true)
  66855. * Should be set to false if shader will overwrite all previous pixels.
  66856. */
  66857. this.autoClear = true;
  66858. /**
  66859. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  66860. */
  66861. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  66862. /**
  66863. * Animations to be used for the post processing
  66864. */
  66865. this.animations = new Array();
  66866. /**
  66867. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  66868. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  66869. */
  66870. this.enablePixelPerfectMode = false;
  66871. /**
  66872. * Force the postprocess to be applied without taking in account viewport
  66873. */
  66874. this.forceFullscreenViewport = true;
  66875. /**
  66876. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  66877. *
  66878. * | Value | Type | Description |
  66879. * | ----- | ----------------------------------- | ----------- |
  66880. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  66881. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  66882. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  66883. *
  66884. */
  66885. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  66886. /**
  66887. * Force textures to be a power of two (default: false)
  66888. */
  66889. this.alwaysForcePOT = false;
  66890. /**
  66891. * Number of sample textures (default: 1)
  66892. */
  66893. this.samples = 1;
  66894. /**
  66895. * Modify the scale of the post process to be the same as the viewport (default: false)
  66896. */
  66897. this.adaptScaleToCurrentViewport = false;
  66898. this._reusable = false;
  66899. /**
  66900. * Smart array of input and output textures for the post process.
  66901. */
  66902. this._textures = new BABYLON.SmartArray(2);
  66903. /**
  66904. * The index in _textures that corresponds to the output texture.
  66905. */
  66906. this._currentRenderTextureInd = 0;
  66907. this._scaleRatio = new BABYLON.Vector2(1, 1);
  66908. this._texelSize = BABYLON.Vector2.Zero();
  66909. // Events
  66910. /**
  66911. * An event triggered when the postprocess is activated.
  66912. */
  66913. this.onActivateObservable = new BABYLON.Observable();
  66914. /**
  66915. * An event triggered when the postprocess changes its size.
  66916. */
  66917. this.onSizeChangedObservable = new BABYLON.Observable();
  66918. /**
  66919. * An event triggered when the postprocess applies its effect.
  66920. */
  66921. this.onApplyObservable = new BABYLON.Observable();
  66922. /**
  66923. * An event triggered before rendering the postprocess
  66924. */
  66925. this.onBeforeRenderObservable = new BABYLON.Observable();
  66926. /**
  66927. * An event triggered after rendering the postprocess
  66928. */
  66929. this.onAfterRenderObservable = new BABYLON.Observable();
  66930. if (camera != null) {
  66931. this._camera = camera;
  66932. this._scene = camera.getScene();
  66933. camera.attachPostProcess(this);
  66934. this._engine = this._scene.getEngine();
  66935. this._scene.postProcesses.push(this);
  66936. }
  66937. else if (engine) {
  66938. this._engine = engine;
  66939. this._engine.postProcesses.push(this);
  66940. }
  66941. this._options = options;
  66942. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  66943. this._reusable = reusable || false;
  66944. this._textureType = textureType;
  66945. this._samplers = samplers || [];
  66946. this._samplers.push("textureSampler");
  66947. this._fragmentUrl = fragmentUrl;
  66948. this._vertexUrl = vertexUrl;
  66949. this._parameters = parameters || [];
  66950. this._parameters.push("scale");
  66951. this._indexParameters = indexParameters;
  66952. if (!blockCompilation) {
  66953. this.updateEffect(defines);
  66954. }
  66955. }
  66956. Object.defineProperty(PostProcess.prototype, "onActivate", {
  66957. /**
  66958. * A function that is added to the onActivateObservable
  66959. */
  66960. set: function (callback) {
  66961. if (this._onActivateObserver) {
  66962. this.onActivateObservable.remove(this._onActivateObserver);
  66963. }
  66964. if (callback) {
  66965. this._onActivateObserver = this.onActivateObservable.add(callback);
  66966. }
  66967. },
  66968. enumerable: true,
  66969. configurable: true
  66970. });
  66971. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  66972. /**
  66973. * A function that is added to the onSizeChangedObservable
  66974. */
  66975. set: function (callback) {
  66976. if (this._onSizeChangedObserver) {
  66977. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  66978. }
  66979. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  66980. },
  66981. enumerable: true,
  66982. configurable: true
  66983. });
  66984. Object.defineProperty(PostProcess.prototype, "onApply", {
  66985. /**
  66986. * A function that is added to the onApplyObservable
  66987. */
  66988. set: function (callback) {
  66989. if (this._onApplyObserver) {
  66990. this.onApplyObservable.remove(this._onApplyObserver);
  66991. }
  66992. this._onApplyObserver = this.onApplyObservable.add(callback);
  66993. },
  66994. enumerable: true,
  66995. configurable: true
  66996. });
  66997. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  66998. /**
  66999. * A function that is added to the onBeforeRenderObservable
  67000. */
  67001. set: function (callback) {
  67002. if (this._onBeforeRenderObserver) {
  67003. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  67004. }
  67005. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  67011. /**
  67012. * A function that is added to the onAfterRenderObservable
  67013. */
  67014. set: function (callback) {
  67015. if (this._onAfterRenderObserver) {
  67016. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  67017. }
  67018. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  67019. },
  67020. enumerable: true,
  67021. configurable: true
  67022. });
  67023. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  67024. /**
  67025. * 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
  67026. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  67027. */
  67028. get: function () {
  67029. return this._textures.data[this._currentRenderTextureInd];
  67030. },
  67031. set: function (value) {
  67032. this._forcedOutputTexture = value;
  67033. },
  67034. enumerable: true,
  67035. configurable: true
  67036. });
  67037. /**
  67038. * Gets the camera which post process is applied to.
  67039. * @returns The camera the post process is applied to.
  67040. */
  67041. PostProcess.prototype.getCamera = function () {
  67042. return this._camera;
  67043. };
  67044. Object.defineProperty(PostProcess.prototype, "texelSize", {
  67045. /**
  67046. * Gets the texel size of the postprocess.
  67047. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  67048. */
  67049. get: function () {
  67050. if (this._shareOutputWithPostProcess) {
  67051. return this._shareOutputWithPostProcess.texelSize;
  67052. }
  67053. if (this._forcedOutputTexture) {
  67054. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  67055. }
  67056. return this._texelSize;
  67057. },
  67058. enumerable: true,
  67059. configurable: true
  67060. });
  67061. /**
  67062. * Gets the engine which this post process belongs to.
  67063. * @returns The engine the post process was enabled with.
  67064. */
  67065. PostProcess.prototype.getEngine = function () {
  67066. return this._engine;
  67067. };
  67068. /**
  67069. * The effect that is created when initializing the post process.
  67070. * @returns The created effect corrisponding the the postprocess.
  67071. */
  67072. PostProcess.prototype.getEffect = function () {
  67073. return this._effect;
  67074. };
  67075. /**
  67076. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  67077. * @param postProcess The post process to share the output with.
  67078. * @returns This post process.
  67079. */
  67080. PostProcess.prototype.shareOutputWith = function (postProcess) {
  67081. this._disposeTextures();
  67082. this._shareOutputWithPostProcess = postProcess;
  67083. return this;
  67084. };
  67085. /**
  67086. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  67087. * This should be called if the post process that shares output with this post process is disabled/disposed.
  67088. */
  67089. PostProcess.prototype.useOwnOutput = function () {
  67090. if (this._textures.length == 0) {
  67091. this._textures = new BABYLON.SmartArray(2);
  67092. }
  67093. this._shareOutputWithPostProcess = null;
  67094. };
  67095. /**
  67096. * Updates the effect with the current post process compile time values and recompiles the shader.
  67097. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  67098. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  67099. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  67100. * @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
  67101. * @param onCompiled Called when the shader has been compiled.
  67102. * @param onError Called if there is an error when compiling a shader.
  67103. */
  67104. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  67105. if (defines === void 0) { defines = null; }
  67106. if (uniforms === void 0) { uniforms = null; }
  67107. if (samplers === void 0) { samplers = null; }
  67108. 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);
  67109. };
  67110. /**
  67111. * The post process is reusable if it can be used multiple times within one frame.
  67112. * @returns If the post process is reusable
  67113. */
  67114. PostProcess.prototype.isReusable = function () {
  67115. return this._reusable;
  67116. };
  67117. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  67118. PostProcess.prototype.markTextureDirty = function () {
  67119. this.width = -1;
  67120. };
  67121. /**
  67122. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  67123. * 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.
  67124. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  67125. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  67126. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  67127. * @returns The target texture that was bound to be written to.
  67128. */
  67129. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  67130. var _this = this;
  67131. if (sourceTexture === void 0) { sourceTexture = null; }
  67132. camera = camera || this._camera;
  67133. var scene = camera.getScene();
  67134. var engine = scene.getEngine();
  67135. var maxSize = engine.getCaps().maxTextureSize;
  67136. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  67137. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  67138. // 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
  67139. var webVRCamera = camera.parent;
  67140. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  67141. requiredWidth /= 2;
  67142. }
  67143. var desiredWidth = (this._options.width || requiredWidth);
  67144. var desiredHeight = this._options.height || requiredHeight;
  67145. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  67146. if (this.adaptScaleToCurrentViewport) {
  67147. var currentViewport = engine.currentViewport;
  67148. if (currentViewport) {
  67149. desiredWidth *= currentViewport.width;
  67150. desiredHeight *= currentViewport.height;
  67151. }
  67152. }
  67153. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  67154. if (!this._options.width) {
  67155. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  67156. }
  67157. if (!this._options.height) {
  67158. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  67159. }
  67160. }
  67161. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  67162. if (this._textures.length > 0) {
  67163. for (var i = 0; i < this._textures.length; i++) {
  67164. this._engine._releaseTexture(this._textures.data[i]);
  67165. }
  67166. this._textures.reset();
  67167. }
  67168. this.width = desiredWidth;
  67169. this.height = desiredHeight;
  67170. var textureSize = { width: this.width, height: this.height };
  67171. var textureOptions = {
  67172. generateMipMaps: false,
  67173. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  67174. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  67175. samplingMode: this.renderTargetSamplingMode,
  67176. type: this._textureType
  67177. };
  67178. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67179. if (this._reusable) {
  67180. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  67181. }
  67182. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  67183. this.onSizeChangedObservable.notifyObservers(this);
  67184. }
  67185. this._textures.forEach(function (texture) {
  67186. if (texture.samples !== _this.samples) {
  67187. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  67188. }
  67189. });
  67190. }
  67191. var target;
  67192. if (this._shareOutputWithPostProcess) {
  67193. target = this._shareOutputWithPostProcess.inputTexture;
  67194. }
  67195. else if (this._forcedOutputTexture) {
  67196. target = this._forcedOutputTexture;
  67197. this.width = this._forcedOutputTexture.width;
  67198. this.height = this._forcedOutputTexture.height;
  67199. }
  67200. else {
  67201. target = this.inputTexture;
  67202. }
  67203. // Bind the input of this post process to be used as the output of the previous post process.
  67204. if (this.enablePixelPerfectMode) {
  67205. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  67206. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  67207. }
  67208. else {
  67209. this._scaleRatio.copyFromFloats(1, 1);
  67210. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  67211. }
  67212. this.onActivateObservable.notifyObservers(camera);
  67213. // Clear
  67214. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  67215. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  67216. }
  67217. if (this._reusable) {
  67218. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  67219. }
  67220. return target;
  67221. };
  67222. Object.defineProperty(PostProcess.prototype, "isSupported", {
  67223. /**
  67224. * If the post process is supported.
  67225. */
  67226. get: function () {
  67227. return this._effect.isSupported;
  67228. },
  67229. enumerable: true,
  67230. configurable: true
  67231. });
  67232. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  67233. /**
  67234. * The aspect ratio of the output texture.
  67235. */
  67236. get: function () {
  67237. if (this._shareOutputWithPostProcess) {
  67238. return this._shareOutputWithPostProcess.aspectRatio;
  67239. }
  67240. if (this._forcedOutputTexture) {
  67241. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  67242. }
  67243. return this.width / this.height;
  67244. },
  67245. enumerable: true,
  67246. configurable: true
  67247. });
  67248. /**
  67249. * Get a value indicating if the post-process is ready to be used
  67250. * @returns true if the post-process is ready (shader is compiled)
  67251. */
  67252. PostProcess.prototype.isReady = function () {
  67253. return this._effect && this._effect.isReady();
  67254. };
  67255. /**
  67256. * Binds all textures and uniforms to the shader, this will be run on every pass.
  67257. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  67258. */
  67259. PostProcess.prototype.apply = function () {
  67260. // Check
  67261. if (!this._effect || !this._effect.isReady())
  67262. return null;
  67263. // States
  67264. this._engine.enableEffect(this._effect);
  67265. this._engine.setState(false);
  67266. this._engine.setDepthBuffer(false);
  67267. this._engine.setDepthWrite(false);
  67268. // Alpha
  67269. this._engine.setAlphaMode(this.alphaMode);
  67270. if (this.alphaConstants) {
  67271. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  67272. }
  67273. // Bind the output texture of the preivous post process as the input to this post process.
  67274. var source;
  67275. if (this._shareOutputWithPostProcess) {
  67276. source = this._shareOutputWithPostProcess.inputTexture;
  67277. }
  67278. else if (this._forcedOutputTexture) {
  67279. source = this._forcedOutputTexture;
  67280. }
  67281. else {
  67282. source = this.inputTexture;
  67283. }
  67284. this._effect._bindTexture("textureSampler", source);
  67285. // Parameters
  67286. this._effect.setVector2("scale", this._scaleRatio);
  67287. this.onApplyObservable.notifyObservers(this._effect);
  67288. return this._effect;
  67289. };
  67290. PostProcess.prototype._disposeTextures = function () {
  67291. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  67292. return;
  67293. }
  67294. if (this._textures.length > 0) {
  67295. for (var i = 0; i < this._textures.length; i++) {
  67296. this._engine._releaseTexture(this._textures.data[i]);
  67297. }
  67298. }
  67299. this._textures.dispose();
  67300. };
  67301. /**
  67302. * Disposes the post process.
  67303. * @param camera The camera to dispose the post process on.
  67304. */
  67305. PostProcess.prototype.dispose = function (camera) {
  67306. camera = camera || this._camera;
  67307. this._disposeTextures();
  67308. if (this._scene) {
  67309. var index_1 = this._scene.postProcesses.indexOf(this);
  67310. if (index_1 !== -1) {
  67311. this._scene.postProcesses.splice(index_1, 1);
  67312. }
  67313. }
  67314. else {
  67315. var index_2 = this._engine.postProcesses.indexOf(this);
  67316. if (index_2 !== -1) {
  67317. this._engine.postProcesses.splice(index_2, 1);
  67318. }
  67319. }
  67320. if (!camera) {
  67321. return;
  67322. }
  67323. camera.detachPostProcess(this);
  67324. var index = camera._postProcesses.indexOf(this);
  67325. if (index === 0 && camera._postProcesses.length > 0) {
  67326. var firstPostProcess = this._camera._getFirstPostProcess();
  67327. if (firstPostProcess) {
  67328. firstPostProcess.markTextureDirty();
  67329. }
  67330. }
  67331. this.onActivateObservable.clear();
  67332. this.onAfterRenderObservable.clear();
  67333. this.onApplyObservable.clear();
  67334. this.onBeforeRenderObservable.clear();
  67335. this.onSizeChangedObservable.clear();
  67336. };
  67337. return PostProcess;
  67338. }());
  67339. BABYLON.PostProcess = PostProcess;
  67340. })(BABYLON || (BABYLON = {}));
  67341. //# sourceMappingURL=babylon.postProcess.js.map
  67342. var BABYLON;
  67343. (function (BABYLON) {
  67344. var PassPostProcess = /** @class */ (function (_super) {
  67345. __extends(PassPostProcess, _super);
  67346. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  67347. if (camera === void 0) { camera = null; }
  67348. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67349. if (blockCompilation === void 0) { blockCompilation = false; }
  67350. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  67351. }
  67352. return PassPostProcess;
  67353. }(BABYLON.PostProcess));
  67354. BABYLON.PassPostProcess = PassPostProcess;
  67355. })(BABYLON || (BABYLON = {}));
  67356. //# sourceMappingURL=babylon.passPostProcess.js.map
  67357. var __assign = (this && this.__assign) || Object.assign || function(t) {
  67358. for (var s, i = 1, n = arguments.length; i < n; i++) {
  67359. s = arguments[i];
  67360. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  67361. t[p] = s[p];
  67362. }
  67363. return t;
  67364. };
  67365. var BABYLON;
  67366. (function (BABYLON) {
  67367. /**
  67368. * Default implementation IShadowGenerator.
  67369. * This is the main object responsible of generating shadows in the framework.
  67370. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  67371. */
  67372. var ShadowGenerator = /** @class */ (function () {
  67373. /**
  67374. * Creates a ShadowGenerator object.
  67375. * A ShadowGenerator is the required tool to use the shadows.
  67376. * Each light casting shadows needs to use its own ShadowGenerator.
  67377. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  67378. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  67379. * @param light The light object generating the shadows.
  67380. * @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.
  67381. */
  67382. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  67383. this._bias = 0.00005;
  67384. this._normalBias = 0;
  67385. this._blurBoxOffset = 1;
  67386. this._blurScale = 2;
  67387. this._blurKernel = 1;
  67388. this._useKernelBlur = false;
  67389. this._filter = ShadowGenerator.FILTER_NONE;
  67390. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  67391. this._contactHardeningLightSizeUVRatio = 0.1;
  67392. this._darkness = 0;
  67393. this._transparencyShadow = false;
  67394. /**
  67395. * Controls the extent to which the shadows fade out at the edge of the frustum
  67396. * Used only by directionals and spots
  67397. */
  67398. this.frustumEdgeFalloff = 0;
  67399. /**
  67400. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  67401. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  67402. * It might on the other hand introduce peter panning.
  67403. */
  67404. this.forceBackFacesOnly = false;
  67405. this._lightDirection = BABYLON.Vector3.Zero();
  67406. this._viewMatrix = BABYLON.Matrix.Zero();
  67407. this._projectionMatrix = BABYLON.Matrix.Zero();
  67408. this._transformMatrix = BABYLON.Matrix.Zero();
  67409. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67410. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  67411. this._currentFaceIndex = 0;
  67412. this._currentFaceIndexCache = 0;
  67413. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  67414. this._mapSize = mapSize;
  67415. this._light = light;
  67416. this._scene = light.getScene();
  67417. light._shadowGenerator = this;
  67418. // Texture type fallback from float to int if not supported.
  67419. var caps = this._scene.getEngine().getCaps();
  67420. if (!useFullFloatFirst) {
  67421. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67422. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67423. }
  67424. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67425. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67426. }
  67427. else {
  67428. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67429. }
  67430. }
  67431. else {
  67432. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  67433. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67434. }
  67435. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  67436. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67437. }
  67438. else {
  67439. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67440. }
  67441. }
  67442. this._initializeGenerator();
  67443. this._applyFilterValues();
  67444. }
  67445. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  67446. /**
  67447. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  67448. */
  67449. get: function () {
  67450. return this._bias;
  67451. },
  67452. /**
  67453. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  67454. */
  67455. set: function (bias) {
  67456. this._bias = bias;
  67457. },
  67458. enumerable: true,
  67459. configurable: true
  67460. });
  67461. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  67462. /**
  67463. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67464. */
  67465. get: function () {
  67466. return this._normalBias;
  67467. },
  67468. /**
  67469. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  67470. */
  67471. set: function (normalBias) {
  67472. this._normalBias = normalBias;
  67473. },
  67474. enumerable: true,
  67475. configurable: true
  67476. });
  67477. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  67478. /**
  67479. * Gets the blur box offset: offset applied during the blur pass.
  67480. * Only usefull if useKernelBlur = false
  67481. */
  67482. get: function () {
  67483. return this._blurBoxOffset;
  67484. },
  67485. /**
  67486. * Sets the blur box offset: offset applied during the blur pass.
  67487. * Only usefull if useKernelBlur = false
  67488. */
  67489. set: function (value) {
  67490. if (this._blurBoxOffset === value) {
  67491. return;
  67492. }
  67493. this._blurBoxOffset = value;
  67494. this._disposeBlurPostProcesses();
  67495. },
  67496. enumerable: true,
  67497. configurable: true
  67498. });
  67499. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  67500. /**
  67501. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  67502. * 2 means half of the size.
  67503. */
  67504. get: function () {
  67505. return this._blurScale;
  67506. },
  67507. /**
  67508. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  67509. * 2 means half of the size.
  67510. */
  67511. set: function (value) {
  67512. if (this._blurScale === value) {
  67513. return;
  67514. }
  67515. this._blurScale = value;
  67516. this._disposeBlurPostProcesses();
  67517. },
  67518. enumerable: true,
  67519. configurable: true
  67520. });
  67521. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  67522. /**
  67523. * Gets the blur kernel: kernel size of the blur pass.
  67524. * Only usefull if useKernelBlur = true
  67525. */
  67526. get: function () {
  67527. return this._blurKernel;
  67528. },
  67529. /**
  67530. * Sets the blur kernel: kernel size of the blur pass.
  67531. * Only usefull if useKernelBlur = true
  67532. */
  67533. set: function (value) {
  67534. if (this._blurKernel === value) {
  67535. return;
  67536. }
  67537. this._blurKernel = value;
  67538. this._disposeBlurPostProcesses();
  67539. },
  67540. enumerable: true,
  67541. configurable: true
  67542. });
  67543. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  67544. /**
  67545. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  67546. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67547. */
  67548. get: function () {
  67549. return this._useKernelBlur;
  67550. },
  67551. /**
  67552. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  67553. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  67554. */
  67555. set: function (value) {
  67556. if (this._useKernelBlur === value) {
  67557. return;
  67558. }
  67559. this._useKernelBlur = value;
  67560. this._disposeBlurPostProcesses();
  67561. },
  67562. enumerable: true,
  67563. configurable: true
  67564. });
  67565. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  67566. /**
  67567. * Gets the depth scale used in ESM mode.
  67568. */
  67569. get: function () {
  67570. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  67571. },
  67572. /**
  67573. * Sets the depth scale used in ESM mode.
  67574. * This can override the scale stored on the light.
  67575. */
  67576. set: function (value) {
  67577. this._depthScale = value;
  67578. },
  67579. enumerable: true,
  67580. configurable: true
  67581. });
  67582. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  67583. /**
  67584. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  67585. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67586. */
  67587. get: function () {
  67588. return this._filter;
  67589. },
  67590. /**
  67591. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  67592. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  67593. */
  67594. set: function (value) {
  67595. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  67596. if (this._light.needCube()) {
  67597. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67598. this.useExponentialShadowMap = true;
  67599. return;
  67600. }
  67601. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67602. this.useCloseExponentialShadowMap = true;
  67603. return;
  67604. }
  67605. // PCF on cubemap would also be expensive
  67606. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67607. this.usePoissonSampling = true;
  67608. return;
  67609. }
  67610. }
  67611. // Weblg1 fallback for PCF.
  67612. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  67613. if (this._scene.getEngine().webGLVersion === 1) {
  67614. this.usePoissonSampling = true;
  67615. return;
  67616. }
  67617. }
  67618. if (this._filter === value) {
  67619. return;
  67620. }
  67621. this._filter = value;
  67622. this._disposeBlurPostProcesses();
  67623. this._applyFilterValues();
  67624. this._light._markMeshesAsLightDirty();
  67625. },
  67626. enumerable: true,
  67627. configurable: true
  67628. });
  67629. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  67630. /**
  67631. * Gets if the current filter is set to Poisson Sampling.
  67632. */
  67633. get: function () {
  67634. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  67635. },
  67636. /**
  67637. * Sets the current filter to Poisson Sampling.
  67638. */
  67639. set: function (value) {
  67640. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  67641. return;
  67642. }
  67643. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  67644. },
  67645. enumerable: true,
  67646. configurable: true
  67647. });
  67648. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  67649. /**
  67650. * Gets if the current filter is set to VSM.
  67651. * DEPRECATED. Should use useExponentialShadowMap instead.
  67652. */
  67653. get: function () {
  67654. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67655. return this.useExponentialShadowMap;
  67656. },
  67657. /**
  67658. * Sets the current filter is to VSM.
  67659. * DEPRECATED. Should use useExponentialShadowMap instead.
  67660. */
  67661. set: function (value) {
  67662. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  67663. this.useExponentialShadowMap = value;
  67664. },
  67665. enumerable: true,
  67666. configurable: true
  67667. });
  67668. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  67669. /**
  67670. * Gets if the current filter is set to blurred VSM.
  67671. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67672. */
  67673. get: function () {
  67674. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67675. return this.useBlurExponentialShadowMap;
  67676. },
  67677. /**
  67678. * Sets the current filter is to blurred VSM.
  67679. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  67680. */
  67681. set: function (value) {
  67682. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  67683. this.useBlurExponentialShadowMap = value;
  67684. },
  67685. enumerable: true,
  67686. configurable: true
  67687. });
  67688. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  67689. /**
  67690. * Gets if the current filter is set to ESM.
  67691. */
  67692. get: function () {
  67693. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  67694. },
  67695. /**
  67696. * Sets the current filter is to ESM.
  67697. */
  67698. set: function (value) {
  67699. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  67700. return;
  67701. }
  67702. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67703. },
  67704. enumerable: true,
  67705. configurable: true
  67706. });
  67707. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  67708. /**
  67709. * Gets if the current filter is set to filtered ESM.
  67710. */
  67711. get: function () {
  67712. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  67713. },
  67714. /**
  67715. * Gets if the current filter is set to filtered ESM.
  67716. */
  67717. set: function (value) {
  67718. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  67719. return;
  67720. }
  67721. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67722. },
  67723. enumerable: true,
  67724. configurable: true
  67725. });
  67726. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  67727. /**
  67728. * Gets if the current filter is set to "close ESM" (using the inverse of the
  67729. * exponential to prevent steep falloff artifacts).
  67730. */
  67731. get: function () {
  67732. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  67733. },
  67734. /**
  67735. * Sets the current filter to "close ESM" (using the inverse of the
  67736. * exponential to prevent steep falloff artifacts).
  67737. */
  67738. set: function (value) {
  67739. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  67740. return;
  67741. }
  67742. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67743. },
  67744. enumerable: true,
  67745. configurable: true
  67746. });
  67747. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  67748. /**
  67749. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  67750. * exponential to prevent steep falloff artifacts).
  67751. */
  67752. get: function () {
  67753. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  67754. },
  67755. /**
  67756. * Sets the current filter to filtered "close ESM" (using the inverse of the
  67757. * exponential to prevent steep falloff artifacts).
  67758. */
  67759. set: function (value) {
  67760. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  67761. return;
  67762. }
  67763. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  67764. },
  67765. enumerable: true,
  67766. configurable: true
  67767. });
  67768. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  67769. /**
  67770. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  67771. */
  67772. get: function () {
  67773. return this.filter === ShadowGenerator.FILTER_PCF;
  67774. },
  67775. /**
  67776. * Sets the current filter to "PCF" (percentage closer filtering).
  67777. */
  67778. set: function (value) {
  67779. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  67780. return;
  67781. }
  67782. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  67783. },
  67784. enumerable: true,
  67785. configurable: true
  67786. });
  67787. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  67788. /**
  67789. * Gets the PCF or PCSS Quality.
  67790. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67791. */
  67792. get: function () {
  67793. return this._filteringQuality;
  67794. },
  67795. /**
  67796. * Sets the PCF or PCSS Quality.
  67797. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  67798. */
  67799. set: function (filteringQuality) {
  67800. this._filteringQuality = filteringQuality;
  67801. },
  67802. enumerable: true,
  67803. configurable: true
  67804. });
  67805. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  67806. /**
  67807. * Gets if the current filter is set to "PCSS" (contact hardening).
  67808. */
  67809. get: function () {
  67810. return this.filter === ShadowGenerator.FILTER_PCSS;
  67811. },
  67812. /**
  67813. * Sets the current filter to "PCSS" (contact hardening).
  67814. */
  67815. set: function (value) {
  67816. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  67817. return;
  67818. }
  67819. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  67820. },
  67821. enumerable: true,
  67822. configurable: true
  67823. });
  67824. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  67825. /**
  67826. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67827. * Using a ratio helps keeping shape stability independently of the map size.
  67828. *
  67829. * It does not account for the light projection as it was having too much
  67830. * instability during the light setup or during light position changes.
  67831. *
  67832. * Only valid if useContactHardeningShadow is true.
  67833. */
  67834. get: function () {
  67835. return this._contactHardeningLightSizeUVRatio;
  67836. },
  67837. /**
  67838. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  67839. * Using a ratio helps keeping shape stability independently of the map size.
  67840. *
  67841. * It does not account for the light projection as it was having too much
  67842. * instability during the light setup or during light position changes.
  67843. *
  67844. * Only valid if useContactHardeningShadow is true.
  67845. */
  67846. set: function (contactHardeningLightSizeUVRatio) {
  67847. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  67848. },
  67849. enumerable: true,
  67850. configurable: true
  67851. });
  67852. /**
  67853. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  67854. * 0 means strongest and 1 would means no shadow.
  67855. * @returns the darkness.
  67856. */
  67857. ShadowGenerator.prototype.getDarkness = function () {
  67858. return this._darkness;
  67859. };
  67860. /**
  67861. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  67862. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  67863. * @returns the shadow generator allowing fluent coding.
  67864. */
  67865. ShadowGenerator.prototype.setDarkness = function (darkness) {
  67866. if (darkness >= 1.0)
  67867. this._darkness = 1.0;
  67868. else if (darkness <= 0.0)
  67869. this._darkness = 0.0;
  67870. else
  67871. this._darkness = darkness;
  67872. return this;
  67873. };
  67874. /**
  67875. * Sets the ability to have transparent shadow (boolean).
  67876. * @param transparent True if transparent else False
  67877. * @returns the shadow generator allowing fluent coding
  67878. */
  67879. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  67880. this._transparencyShadow = transparent;
  67881. return this;
  67882. };
  67883. /**
  67884. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  67885. * @returns The render target texture if present otherwise, null
  67886. */
  67887. ShadowGenerator.prototype.getShadowMap = function () {
  67888. return this._shadowMap;
  67889. };
  67890. /**
  67891. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  67892. * @returns The render target texture if the shadow map is present otherwise, null
  67893. */
  67894. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  67895. if (this._shadowMap2) {
  67896. return this._shadowMap2;
  67897. }
  67898. return this._shadowMap;
  67899. };
  67900. /**
  67901. * Helper function to add a mesh and its descendants to the list of shadow casters.
  67902. * @param mesh Mesh to add
  67903. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  67904. * @returns the Shadow Generator itself
  67905. */
  67906. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  67907. if (includeDescendants === void 0) { includeDescendants = true; }
  67908. if (!this._shadowMap) {
  67909. return this;
  67910. }
  67911. if (!this._shadowMap.renderList) {
  67912. this._shadowMap.renderList = [];
  67913. }
  67914. this._shadowMap.renderList.push(mesh);
  67915. if (includeDescendants) {
  67916. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  67917. }
  67918. return this;
  67919. var _a;
  67920. };
  67921. /**
  67922. * Helper function to remove a mesh and its descendants from the list of shadow casters
  67923. * @param mesh Mesh to remove
  67924. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  67925. * @returns the Shadow Generator itself
  67926. */
  67927. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  67928. if (includeDescendants === void 0) { includeDescendants = true; }
  67929. if (!this._shadowMap || !this._shadowMap.renderList) {
  67930. return this;
  67931. }
  67932. var index = this._shadowMap.renderList.indexOf(mesh);
  67933. if (index !== -1) {
  67934. this._shadowMap.renderList.splice(index, 1);
  67935. }
  67936. if (includeDescendants) {
  67937. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  67938. var child = _a[_i];
  67939. this.removeShadowCaster(child);
  67940. }
  67941. }
  67942. return this;
  67943. };
  67944. /**
  67945. * Returns the associated light object.
  67946. * @returns the light generating the shadow
  67947. */
  67948. ShadowGenerator.prototype.getLight = function () {
  67949. return this._light;
  67950. };
  67951. ShadowGenerator.prototype._initializeGenerator = function () {
  67952. this._light._markMeshesAsLightDirty();
  67953. this._initializeShadowMap();
  67954. };
  67955. ShadowGenerator.prototype._initializeShadowMap = function () {
  67956. var _this = this;
  67957. // Render target
  67958. var engine = this._scene.getEngine();
  67959. if (engine.webGLVersion > 1) {
  67960. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  67961. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  67962. }
  67963. else {
  67964. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  67965. }
  67966. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67967. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67968. this._shadowMap.anisotropicFilteringLevel = 1;
  67969. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67970. this._shadowMap.renderParticles = false;
  67971. this._shadowMap.ignoreCameraViewport = true;
  67972. // Record Face Index before render.
  67973. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  67974. _this._currentFaceIndex = faceIndex;
  67975. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67976. engine.setColorWrite(false);
  67977. }
  67978. });
  67979. // Custom render function.
  67980. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  67981. // Blur if required afer render.
  67982. this._shadowMap.onAfterUnbindObservable.add(function () {
  67983. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67984. engine.setColorWrite(true);
  67985. }
  67986. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  67987. return;
  67988. }
  67989. var shadowMap = _this.getShadowMapForRendering();
  67990. if (shadowMap) {
  67991. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  67992. }
  67993. });
  67994. // Clear according to the chosen filter.
  67995. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  67996. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  67997. this._shadowMap.onClearObservable.add(function (engine) {
  67998. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  67999. engine.clear(clearOne, false, true, false);
  68000. }
  68001. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  68002. engine.clear(clearZero, true, true, false);
  68003. }
  68004. else {
  68005. engine.clear(clearOne, true, true, false);
  68006. }
  68007. });
  68008. };
  68009. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  68010. var _this = this;
  68011. var engine = this._scene.getEngine();
  68012. var targetSize = this._mapSize / this.blurScale;
  68013. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  68014. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  68015. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68016. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68017. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68018. }
  68019. if (this.useKernelBlur) {
  68020. 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);
  68021. this._kernelBlurXPostprocess.width = targetSize;
  68022. this._kernelBlurXPostprocess.height = targetSize;
  68023. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  68024. effect.setTexture("textureSampler", _this._shadowMap);
  68025. });
  68026. 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);
  68027. this._kernelBlurXPostprocess.autoClear = false;
  68028. this._kernelBlurYPostprocess.autoClear = false;
  68029. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68030. this._kernelBlurXPostprocess.packedFloat = true;
  68031. this._kernelBlurYPostprocess.packedFloat = true;
  68032. }
  68033. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  68034. }
  68035. else {
  68036. 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);
  68037. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  68038. effect.setFloat2("screenSize", targetSize, targetSize);
  68039. effect.setTexture("textureSampler", _this._shadowMap);
  68040. });
  68041. this._boxBlurPostprocess.autoClear = false;
  68042. this._blurPostProcesses = [this._boxBlurPostprocess];
  68043. }
  68044. };
  68045. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68046. var index;
  68047. var engine = this._scene.getEngine();
  68048. if (depthOnlySubMeshes.length) {
  68049. engine.setColorWrite(false);
  68050. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68051. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  68052. }
  68053. engine.setColorWrite(true);
  68054. }
  68055. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68056. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  68057. }
  68058. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68059. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  68060. }
  68061. if (this._transparencyShadow) {
  68062. for (index = 0; index < transparentSubMeshes.length; index++) {
  68063. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  68064. }
  68065. }
  68066. };
  68067. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  68068. var _this = this;
  68069. var mesh = subMesh.getRenderingMesh();
  68070. var scene = this._scene;
  68071. var engine = scene.getEngine();
  68072. var material = subMesh.getMaterial();
  68073. if (!material) {
  68074. return;
  68075. }
  68076. // Culling
  68077. engine.setState(material.backFaceCulling);
  68078. // Managing instances
  68079. var batch = mesh._getInstancesRenderList(subMesh._id);
  68080. if (batch.mustReturn) {
  68081. return;
  68082. }
  68083. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  68084. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  68085. engine.enableEffect(this._effect);
  68086. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  68087. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  68088. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  68089. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68090. this._effect.setVector3("lightData", this._cachedDirection);
  68091. }
  68092. else {
  68093. this._effect.setVector3("lightData", this._cachedPosition);
  68094. }
  68095. if (scene.activeCamera) {
  68096. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  68097. }
  68098. // Alpha test
  68099. if (material && material.needAlphaTesting()) {
  68100. var alphaTexture = material.getAlphaTestTexture();
  68101. if (alphaTexture) {
  68102. this._effect.setTexture("diffuseSampler", alphaTexture);
  68103. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  68104. }
  68105. }
  68106. // Bones
  68107. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68108. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  68109. }
  68110. // Morph targets
  68111. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  68112. if (this.forceBackFacesOnly) {
  68113. engine.setState(true, 0, false, true);
  68114. }
  68115. // Draw
  68116. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68117. if (this.forceBackFacesOnly) {
  68118. engine.setState(true, 0, false, false);
  68119. }
  68120. }
  68121. else {
  68122. // Need to reset refresh rate of the shadowMap
  68123. if (this._shadowMap) {
  68124. this._shadowMap.resetRefreshCounter();
  68125. }
  68126. }
  68127. };
  68128. ShadowGenerator.prototype._applyFilterValues = function () {
  68129. if (!this._shadowMap) {
  68130. return;
  68131. }
  68132. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  68133. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  68134. }
  68135. else {
  68136. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68137. }
  68138. };
  68139. /**
  68140. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68141. * @param onCompiled Callback triggered at the and of the effects compilation
  68142. * @param options Sets of optional options forcing the compilation with different modes
  68143. */
  68144. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  68145. var _this = this;
  68146. var localOptions = __assign({ useInstances: false }, options);
  68147. var shadowMap = this.getShadowMap();
  68148. if (!shadowMap) {
  68149. if (onCompiled) {
  68150. onCompiled(this);
  68151. }
  68152. return;
  68153. }
  68154. var renderList = shadowMap.renderList;
  68155. if (!renderList) {
  68156. if (onCompiled) {
  68157. onCompiled(this);
  68158. }
  68159. return;
  68160. }
  68161. var subMeshes = new Array();
  68162. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  68163. var mesh = renderList_1[_i];
  68164. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  68165. }
  68166. if (subMeshes.length === 0) {
  68167. if (onCompiled) {
  68168. onCompiled(this);
  68169. }
  68170. return;
  68171. }
  68172. var currentIndex = 0;
  68173. var checkReady = function () {
  68174. if (!_this._scene || !_this._scene.getEngine()) {
  68175. return;
  68176. }
  68177. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  68178. currentIndex++;
  68179. if (currentIndex >= subMeshes.length) {
  68180. if (onCompiled) {
  68181. onCompiled(_this);
  68182. }
  68183. return;
  68184. }
  68185. }
  68186. setTimeout(checkReady, 16);
  68187. };
  68188. checkReady();
  68189. };
  68190. /**
  68191. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  68192. * @param options Sets of optional options forcing the compilation with different modes
  68193. * @returns A promise that resolves when the compilation completes
  68194. */
  68195. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  68196. var _this = this;
  68197. return new Promise(function (resolve) {
  68198. _this.forceCompilation(function () {
  68199. resolve();
  68200. }, options);
  68201. });
  68202. };
  68203. /**
  68204. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  68205. * @param subMesh The submesh we want to render in the shadow map
  68206. * @param useInstances Defines wether will draw in the map using instances
  68207. * @returns true if ready otherwise, false
  68208. */
  68209. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  68210. var defines = [];
  68211. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  68212. defines.push("#define FLOAT");
  68213. }
  68214. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68215. defines.push("#define ESM");
  68216. }
  68217. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  68218. defines.push("#define DEPTHTEXTURE");
  68219. }
  68220. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68221. var mesh = subMesh.getMesh();
  68222. var material = subMesh.getMaterial();
  68223. // Normal bias.
  68224. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68225. attribs.push(BABYLON.VertexBuffer.NormalKind);
  68226. defines.push("#define NORMAL");
  68227. if (mesh.nonUniformScaling) {
  68228. defines.push("#define NONUNIFORMSCALING");
  68229. }
  68230. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  68231. defines.push("#define DIRECTIONINLIGHTDATA");
  68232. }
  68233. }
  68234. // Alpha test
  68235. if (material && material.needAlphaTesting()) {
  68236. var alphaTexture = material.getAlphaTestTexture();
  68237. if (alphaTexture) {
  68238. defines.push("#define ALPHATEST");
  68239. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68240. attribs.push(BABYLON.VertexBuffer.UVKind);
  68241. defines.push("#define UV1");
  68242. }
  68243. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68244. if (alphaTexture.coordinatesIndex === 1) {
  68245. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68246. defines.push("#define UV2");
  68247. }
  68248. }
  68249. }
  68250. }
  68251. // Bones
  68252. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68253. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68254. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68255. if (mesh.numBoneInfluencers > 4) {
  68256. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68257. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68258. }
  68259. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68260. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  68261. }
  68262. else {
  68263. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68264. }
  68265. // Morph targets
  68266. var manager = mesh.morphTargetManager;
  68267. var morphInfluencers = 0;
  68268. if (manager) {
  68269. if (manager.numInfluencers > 0) {
  68270. defines.push("#define MORPHTARGETS");
  68271. morphInfluencers = manager.numInfluencers;
  68272. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  68273. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  68274. }
  68275. }
  68276. // Instances
  68277. if (useInstances) {
  68278. defines.push("#define INSTANCES");
  68279. attribs.push("world0");
  68280. attribs.push("world1");
  68281. attribs.push("world2");
  68282. attribs.push("world3");
  68283. }
  68284. // Get correct effect
  68285. var join = defines.join("\n");
  68286. if (this._cachedDefines !== join) {
  68287. this._cachedDefines = join;
  68288. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  68289. }
  68290. if (!this._effect.isReady()) {
  68291. return false;
  68292. }
  68293. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68294. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  68295. this._initializeBlurRTTAndPostProcesses();
  68296. }
  68297. }
  68298. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  68299. return false;
  68300. }
  68301. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  68302. return false;
  68303. }
  68304. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  68305. return false;
  68306. }
  68307. return true;
  68308. };
  68309. /**
  68310. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  68311. * @param defines Defines of the material we want to update
  68312. * @param lightIndex Index of the light in the enabled light list of the material
  68313. */
  68314. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  68315. var scene = this._scene;
  68316. var light = this._light;
  68317. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68318. return;
  68319. }
  68320. defines["SHADOW" + lightIndex] = true;
  68321. if (this.useContactHardeningShadow) {
  68322. defines["SHADOWPCSS" + lightIndex] = true;
  68323. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68324. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68325. }
  68326. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68327. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68328. }
  68329. // else default to high.
  68330. }
  68331. if (this.usePercentageCloserFiltering) {
  68332. defines["SHADOWPCF" + lightIndex] = true;
  68333. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  68334. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  68335. }
  68336. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  68337. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  68338. }
  68339. // else default to high.
  68340. }
  68341. else if (this.usePoissonSampling) {
  68342. defines["SHADOWPOISSON" + lightIndex] = true;
  68343. }
  68344. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  68345. defines["SHADOWESM" + lightIndex] = true;
  68346. }
  68347. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  68348. defines["SHADOWCLOSEESM" + lightIndex] = true;
  68349. }
  68350. if (light.needCube()) {
  68351. defines["SHADOWCUBE" + lightIndex] = true;
  68352. }
  68353. };
  68354. /**
  68355. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  68356. * defined in the generator but impacting the effect).
  68357. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  68358. * @param effect The effect we are binfing the information for
  68359. */
  68360. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  68361. var light = this._light;
  68362. var scene = this._scene;
  68363. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  68364. return;
  68365. }
  68366. var camera = scene.activeCamera;
  68367. if (!camera) {
  68368. return;
  68369. }
  68370. var shadowMap = this.getShadowMap();
  68371. if (!shadowMap) {
  68372. return;
  68373. }
  68374. if (!light.needCube()) {
  68375. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  68376. }
  68377. // Only PCF uses depth stencil texture.
  68378. if (this._filter === ShadowGenerator.FILTER_PCF) {
  68379. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68380. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68381. }
  68382. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  68383. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68384. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  68385. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  68386. }
  68387. else {
  68388. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  68389. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  68390. }
  68391. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  68392. };
  68393. /**
  68394. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  68395. * (eq to shadow prjection matrix * light transform matrix)
  68396. * @returns The transform matrix used to create the shadow map
  68397. */
  68398. ShadowGenerator.prototype.getTransformMatrix = function () {
  68399. var scene = this._scene;
  68400. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  68401. return this._transformMatrix;
  68402. }
  68403. this._currentRenderID = scene.getRenderId();
  68404. this._currentFaceIndexCache = this._currentFaceIndex;
  68405. var lightPosition = this._light.position;
  68406. if (this._light.computeTransformedInformation()) {
  68407. lightPosition = this._light.transformedPosition;
  68408. }
  68409. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  68410. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  68411. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  68412. }
  68413. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  68414. this._cachedPosition.copyFrom(lightPosition);
  68415. this._cachedDirection.copyFrom(this._lightDirection);
  68416. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  68417. var shadowMap = this.getShadowMap();
  68418. if (shadowMap) {
  68419. var renderList = shadowMap.renderList;
  68420. if (renderList) {
  68421. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  68422. }
  68423. }
  68424. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  68425. }
  68426. return this._transformMatrix;
  68427. };
  68428. /**
  68429. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  68430. * Cube and 2D textures for instance.
  68431. */
  68432. ShadowGenerator.prototype.recreateShadowMap = function () {
  68433. var shadowMap = this._shadowMap;
  68434. if (!shadowMap) {
  68435. return;
  68436. }
  68437. // Track render list.
  68438. var renderList = shadowMap.renderList;
  68439. // Clean up existing data.
  68440. this._disposeRTTandPostProcesses();
  68441. // Reinitializes.
  68442. this._initializeGenerator();
  68443. // Reaffect the filter to ensure a correct fallback if necessary.
  68444. this.filter = this.filter;
  68445. // Reaffect the filter.
  68446. this._applyFilterValues();
  68447. // Reaffect Render List.
  68448. this._shadowMap.renderList = renderList;
  68449. };
  68450. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  68451. if (this._shadowMap2) {
  68452. this._shadowMap2.dispose();
  68453. this._shadowMap2 = null;
  68454. }
  68455. if (this._boxBlurPostprocess) {
  68456. this._boxBlurPostprocess.dispose();
  68457. this._boxBlurPostprocess = null;
  68458. }
  68459. if (this._kernelBlurXPostprocess) {
  68460. this._kernelBlurXPostprocess.dispose();
  68461. this._kernelBlurXPostprocess = null;
  68462. }
  68463. if (this._kernelBlurYPostprocess) {
  68464. this._kernelBlurYPostprocess.dispose();
  68465. this._kernelBlurYPostprocess = null;
  68466. }
  68467. this._blurPostProcesses = [];
  68468. };
  68469. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  68470. if (this._shadowMap) {
  68471. this._shadowMap.dispose();
  68472. this._shadowMap = null;
  68473. }
  68474. this._disposeBlurPostProcesses();
  68475. };
  68476. /**
  68477. * Disposes the ShadowGenerator.
  68478. * Returns nothing.
  68479. */
  68480. ShadowGenerator.prototype.dispose = function () {
  68481. this._disposeRTTandPostProcesses();
  68482. if (this._light) {
  68483. this._light._shadowGenerator = null;
  68484. this._light._markMeshesAsLightDirty();
  68485. }
  68486. };
  68487. /**
  68488. * Serializes the shadow generator setup to a json object.
  68489. * @returns The serialized JSON object
  68490. */
  68491. ShadowGenerator.prototype.serialize = function () {
  68492. var serializationObject = {};
  68493. var shadowMap = this.getShadowMap();
  68494. if (!shadowMap) {
  68495. return serializationObject;
  68496. }
  68497. serializationObject.lightId = this._light.id;
  68498. serializationObject.mapSize = shadowMap.getRenderSize();
  68499. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  68500. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  68501. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68502. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  68503. serializationObject.usePoissonSampling = this.usePoissonSampling;
  68504. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  68505. serializationObject.depthScale = this.depthScale;
  68506. serializationObject.darkness = this.getDarkness();
  68507. serializationObject.blurBoxOffset = this.blurBoxOffset;
  68508. serializationObject.blurKernel = this.blurKernel;
  68509. serializationObject.blurScale = this.blurScale;
  68510. serializationObject.useKernelBlur = this.useKernelBlur;
  68511. serializationObject.transparencyShadow = this._transparencyShadow;
  68512. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  68513. serializationObject.bias = this.bias;
  68514. serializationObject.normalBias = this.normalBias;
  68515. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  68516. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  68517. serializationObject.filteringQuality = this.filteringQuality;
  68518. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  68519. serializationObject.renderList = [];
  68520. if (shadowMap.renderList) {
  68521. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  68522. var mesh = shadowMap.renderList[meshIndex];
  68523. serializationObject.renderList.push(mesh.id);
  68524. }
  68525. }
  68526. return serializationObject;
  68527. };
  68528. /**
  68529. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  68530. * @param parsedShadowGenerator The JSON object to parse
  68531. * @param scene The scene to create the shadow map for
  68532. * @returns The parsed shadow generator
  68533. */
  68534. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  68535. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  68536. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  68537. var shadowMap = shadowGenerator.getShadowMap();
  68538. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  68539. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  68540. meshes.forEach(function (mesh) {
  68541. if (!shadowMap) {
  68542. return;
  68543. }
  68544. if (!shadowMap.renderList) {
  68545. shadowMap.renderList = [];
  68546. }
  68547. shadowMap.renderList.push(mesh);
  68548. });
  68549. }
  68550. if (parsedShadowGenerator.usePoissonSampling) {
  68551. shadowGenerator.usePoissonSampling = true;
  68552. }
  68553. else if (parsedShadowGenerator.useExponentialShadowMap) {
  68554. shadowGenerator.useExponentialShadowMap = true;
  68555. }
  68556. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  68557. shadowGenerator.useBlurExponentialShadowMap = true;
  68558. }
  68559. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  68560. shadowGenerator.useCloseExponentialShadowMap = true;
  68561. }
  68562. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  68563. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  68564. }
  68565. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  68566. shadowGenerator.usePercentageCloserFiltering = true;
  68567. }
  68568. else if (parsedShadowGenerator.useContactHardeningShadow) {
  68569. shadowGenerator.useContactHardeningShadow = true;
  68570. }
  68571. if (parsedShadowGenerator.filteringQuality) {
  68572. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  68573. }
  68574. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  68575. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  68576. }
  68577. // Backward compat
  68578. else if (parsedShadowGenerator.useVarianceShadowMap) {
  68579. shadowGenerator.useExponentialShadowMap = true;
  68580. }
  68581. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  68582. shadowGenerator.useBlurExponentialShadowMap = true;
  68583. }
  68584. if (parsedShadowGenerator.depthScale) {
  68585. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  68586. }
  68587. if (parsedShadowGenerator.blurScale) {
  68588. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  68589. }
  68590. if (parsedShadowGenerator.blurBoxOffset) {
  68591. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  68592. }
  68593. if (parsedShadowGenerator.useKernelBlur) {
  68594. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  68595. }
  68596. if (parsedShadowGenerator.blurKernel) {
  68597. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  68598. }
  68599. if (parsedShadowGenerator.bias !== undefined) {
  68600. shadowGenerator.bias = parsedShadowGenerator.bias;
  68601. }
  68602. if (parsedShadowGenerator.normalBias !== undefined) {
  68603. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  68604. }
  68605. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  68606. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  68607. }
  68608. if (parsedShadowGenerator.darkness) {
  68609. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  68610. }
  68611. if (parsedShadowGenerator.transparencyShadow) {
  68612. shadowGenerator.setTransparencyShadow(true);
  68613. }
  68614. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  68615. return shadowGenerator;
  68616. };
  68617. /**
  68618. * Shadow generator mode None: no filtering applied.
  68619. */
  68620. ShadowGenerator.FILTER_NONE = 0;
  68621. /**
  68622. * Shadow generator mode ESM: Exponential Shadow Mapping.
  68623. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68624. */
  68625. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  68626. /**
  68627. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  68628. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  68629. */
  68630. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  68631. /**
  68632. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  68633. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68634. */
  68635. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  68636. /**
  68637. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  68638. * edge artifacts on steep falloff.
  68639. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68640. */
  68641. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  68642. /**
  68643. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  68644. * edge artifacts on steep falloff.
  68645. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  68646. */
  68647. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  68648. /**
  68649. * Shadow generator mode PCF: Percentage Closer Filtering
  68650. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68651. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  68652. */
  68653. ShadowGenerator.FILTER_PCF = 6;
  68654. /**
  68655. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  68656. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  68657. * Contact Hardening
  68658. */
  68659. ShadowGenerator.FILTER_PCSS = 7;
  68660. /**
  68661. * Reserved for PCF and PCSS
  68662. * Highest Quality.
  68663. *
  68664. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  68665. *
  68666. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  68667. */
  68668. ShadowGenerator.QUALITY_HIGH = 0;
  68669. /**
  68670. * Reserved for PCF and PCSS
  68671. * Good tradeoff for quality/perf cross devices
  68672. *
  68673. * Execute PCF on a 3*3 kernel.
  68674. *
  68675. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  68676. */
  68677. ShadowGenerator.QUALITY_MEDIUM = 1;
  68678. /**
  68679. * Reserved for PCF and PCSS
  68680. * The lowest quality but the fastest.
  68681. *
  68682. * Execute PCF on a 1*1 kernel.
  68683. *
  68684. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  68685. */
  68686. ShadowGenerator.QUALITY_LOW = 2;
  68687. return ShadowGenerator;
  68688. }());
  68689. BABYLON.ShadowGenerator = ShadowGenerator;
  68690. })(BABYLON || (BABYLON = {}));
  68691. //# sourceMappingURL=babylon.shadowGenerator.js.map
  68692. var BABYLON;
  68693. (function (BABYLON) {
  68694. var DefaultLoadingScreen = /** @class */ (function () {
  68695. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  68696. if (_loadingText === void 0) { _loadingText = ""; }
  68697. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  68698. var _this = this;
  68699. this._renderingCanvas = _renderingCanvas;
  68700. this._loadingText = _loadingText;
  68701. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  68702. // Resize
  68703. this._resizeLoadingUI = function () {
  68704. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  68705. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  68706. if (!_this._loadingDiv) {
  68707. return;
  68708. }
  68709. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  68710. _this._loadingDiv.style.left = canvasRect.left + "px";
  68711. _this._loadingDiv.style.top = canvasRect.top + "px";
  68712. _this._loadingDiv.style.width = canvasRect.width + "px";
  68713. _this._loadingDiv.style.height = canvasRect.height + "px";
  68714. };
  68715. }
  68716. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  68717. if (this._loadingDiv) {
  68718. // Do not add a loading screen if there is already one
  68719. return;
  68720. }
  68721. this._loadingDiv = document.createElement("div");
  68722. this._loadingDiv.id = "babylonjsLoadingDiv";
  68723. this._loadingDiv.style.opacity = "0";
  68724. this._loadingDiv.style.transition = "opacity 1.5s ease";
  68725. this._loadingDiv.style.pointerEvents = "none";
  68726. // Loading text
  68727. this._loadingTextDiv = document.createElement("div");
  68728. this._loadingTextDiv.style.position = "absolute";
  68729. this._loadingTextDiv.style.left = "0";
  68730. this._loadingTextDiv.style.top = "50%";
  68731. this._loadingTextDiv.style.marginTop = "80px";
  68732. this._loadingTextDiv.style.width = "100%";
  68733. this._loadingTextDiv.style.height = "20px";
  68734. this._loadingTextDiv.style.fontFamily = "Arial";
  68735. this._loadingTextDiv.style.fontSize = "14px";
  68736. this._loadingTextDiv.style.color = "white";
  68737. this._loadingTextDiv.style.textAlign = "center";
  68738. this._loadingTextDiv.innerHTML = "Loading";
  68739. this._loadingDiv.appendChild(this._loadingTextDiv);
  68740. //set the predefined text
  68741. this._loadingTextDiv.innerHTML = this._loadingText;
  68742. // Generating keyframes
  68743. var style = document.createElement('style');
  68744. style.type = 'text/css';
  68745. 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 }";
  68746. style.innerHTML = keyFrames;
  68747. document.getElementsByTagName('head')[0].appendChild(style);
  68748. // Loading img
  68749. var imgBack = new Image();
  68750. 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";
  68751. imgBack.style.position = "absolute";
  68752. imgBack.style.left = "50%";
  68753. imgBack.style.top = "50%";
  68754. imgBack.style.marginLeft = "-60px";
  68755. imgBack.style.marginTop = "-60px";
  68756. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  68757. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  68758. imgBack.style.transformOrigin = "50% 50%";
  68759. imgBack.style.webkitTransformOrigin = "50% 50%";
  68760. this._loadingDiv.appendChild(imgBack);
  68761. this._resizeLoadingUI();
  68762. window.addEventListener("resize", this._resizeLoadingUI);
  68763. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68764. document.body.appendChild(this._loadingDiv);
  68765. this._loadingDiv.style.opacity = "1";
  68766. };
  68767. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  68768. var _this = this;
  68769. if (!this._loadingDiv) {
  68770. return;
  68771. }
  68772. var onTransitionEnd = function () {
  68773. if (!_this._loadingDiv) {
  68774. return;
  68775. }
  68776. document.body.removeChild(_this._loadingDiv);
  68777. window.removeEventListener("resize", _this._resizeLoadingUI);
  68778. _this._loadingDiv = null;
  68779. };
  68780. this._loadingDiv.style.opacity = "0";
  68781. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  68782. };
  68783. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  68784. set: function (text) {
  68785. this._loadingText = text;
  68786. if (this._loadingTextDiv) {
  68787. this._loadingTextDiv.innerHTML = this._loadingText;
  68788. }
  68789. },
  68790. enumerable: true,
  68791. configurable: true
  68792. });
  68793. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  68794. get: function () {
  68795. return this._loadingDivBackgroundColor;
  68796. },
  68797. set: function (color) {
  68798. this._loadingDivBackgroundColor = color;
  68799. if (!this._loadingDiv) {
  68800. return;
  68801. }
  68802. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  68803. },
  68804. enumerable: true,
  68805. configurable: true
  68806. });
  68807. return DefaultLoadingScreen;
  68808. }());
  68809. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  68810. })(BABYLON || (BABYLON = {}));
  68811. //# sourceMappingURL=babylon.loadingScreen.js.map
  68812. var BABYLON;
  68813. (function (BABYLON) {
  68814. var SceneLoaderProgressEvent = /** @class */ (function () {
  68815. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  68816. this.lengthComputable = lengthComputable;
  68817. this.loaded = loaded;
  68818. this.total = total;
  68819. }
  68820. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  68821. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  68822. };
  68823. return SceneLoaderProgressEvent;
  68824. }());
  68825. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  68826. var SceneLoader = /** @class */ (function () {
  68827. function SceneLoader() {
  68828. }
  68829. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  68830. get: function () {
  68831. return 0;
  68832. },
  68833. enumerable: true,
  68834. configurable: true
  68835. });
  68836. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  68837. get: function () {
  68838. return 1;
  68839. },
  68840. enumerable: true,
  68841. configurable: true
  68842. });
  68843. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  68844. get: function () {
  68845. return 2;
  68846. },
  68847. enumerable: true,
  68848. configurable: true
  68849. });
  68850. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  68851. get: function () {
  68852. return 3;
  68853. },
  68854. enumerable: true,
  68855. configurable: true
  68856. });
  68857. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  68858. get: function () {
  68859. return SceneLoader._ForceFullSceneLoadingForIncremental;
  68860. },
  68861. set: function (value) {
  68862. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  68863. },
  68864. enumerable: true,
  68865. configurable: true
  68866. });
  68867. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  68868. get: function () {
  68869. return SceneLoader._ShowLoadingScreen;
  68870. },
  68871. set: function (value) {
  68872. SceneLoader._ShowLoadingScreen = value;
  68873. },
  68874. enumerable: true,
  68875. configurable: true
  68876. });
  68877. Object.defineProperty(SceneLoader, "loggingLevel", {
  68878. get: function () {
  68879. return SceneLoader._loggingLevel;
  68880. },
  68881. set: function (value) {
  68882. SceneLoader._loggingLevel = value;
  68883. },
  68884. enumerable: true,
  68885. configurable: true
  68886. });
  68887. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  68888. get: function () {
  68889. return SceneLoader._CleanBoneMatrixWeights;
  68890. },
  68891. set: function (value) {
  68892. SceneLoader._CleanBoneMatrixWeights = value;
  68893. },
  68894. enumerable: true,
  68895. configurable: true
  68896. });
  68897. SceneLoader._getDefaultPlugin = function () {
  68898. return SceneLoader._registeredPlugins[".babylon"];
  68899. };
  68900. SceneLoader._getPluginForExtension = function (extension) {
  68901. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  68902. if (registeredPlugin) {
  68903. return registeredPlugin;
  68904. }
  68905. 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");
  68906. return SceneLoader._getDefaultPlugin();
  68907. };
  68908. SceneLoader._getPluginForDirectLoad = function (data) {
  68909. for (var extension in SceneLoader._registeredPlugins) {
  68910. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  68911. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  68912. return SceneLoader._registeredPlugins[extension];
  68913. }
  68914. }
  68915. return SceneLoader._getDefaultPlugin();
  68916. };
  68917. SceneLoader._getPluginForFilename = function (sceneFilename) {
  68918. if (sceneFilename.name) {
  68919. sceneFilename = sceneFilename.name;
  68920. }
  68921. var queryStringPosition = sceneFilename.indexOf("?");
  68922. if (queryStringPosition !== -1) {
  68923. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  68924. }
  68925. var dotPosition = sceneFilename.lastIndexOf(".");
  68926. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  68927. return SceneLoader._getPluginForExtension(extension);
  68928. };
  68929. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  68930. SceneLoader._getDirectLoad = function (sceneFilename) {
  68931. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  68932. return sceneFilename.substr(5);
  68933. }
  68934. return null;
  68935. };
  68936. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  68937. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  68938. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  68939. var plugin;
  68940. if (registeredPlugin.plugin.createPlugin) {
  68941. plugin = registeredPlugin.plugin.createPlugin();
  68942. }
  68943. else {
  68944. plugin = registeredPlugin.plugin;
  68945. }
  68946. var useArrayBuffer = registeredPlugin.isBinary;
  68947. var database;
  68948. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  68949. var dataCallback = function (data, responseURL) {
  68950. if (scene.isDisposed) {
  68951. onError("Scene has been disposed");
  68952. return;
  68953. }
  68954. scene.database = database;
  68955. onSuccess(plugin, data, responseURL);
  68956. };
  68957. var request = null;
  68958. var pluginDisposed = false;
  68959. var onDisposeObservable = plugin.onDisposeObservable;
  68960. if (onDisposeObservable) {
  68961. onDisposeObservable.add(function () {
  68962. pluginDisposed = true;
  68963. if (request) {
  68964. request.abort();
  68965. request = null;
  68966. }
  68967. onDispose();
  68968. });
  68969. }
  68970. var manifestChecked = function () {
  68971. if (pluginDisposed) {
  68972. return;
  68973. }
  68974. var url = rootUrl + sceneFilename;
  68975. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  68976. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  68977. } : undefined, database, useArrayBuffer, function (request, exception) {
  68978. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  68979. });
  68980. };
  68981. if (directLoad) {
  68982. dataCallback(directLoad);
  68983. return plugin;
  68984. }
  68985. if (rootUrl.indexOf("file:") === -1) {
  68986. var engine = scene.getEngine();
  68987. var canUseOfflineSupport = engine.enableOfflineSupport;
  68988. if (canUseOfflineSupport) {
  68989. // Also check for exceptions
  68990. var exceptionFound = false;
  68991. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  68992. var regex = _a[_i];
  68993. if (regex.test(rootUrl + sceneFilename)) {
  68994. exceptionFound = true;
  68995. break;
  68996. }
  68997. }
  68998. canUseOfflineSupport = !exceptionFound;
  68999. }
  69000. if (canUseOfflineSupport) {
  69001. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  69002. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  69003. }
  69004. else {
  69005. manifestChecked();
  69006. }
  69007. }
  69008. // Loading file from disk via input file or drag'n'drop
  69009. else {
  69010. var fileOrString = sceneFilename;
  69011. if (fileOrString.name) { // File
  69012. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  69013. }
  69014. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  69015. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  69016. }
  69017. else {
  69018. onError("Unable to find file named " + sceneFilename);
  69019. }
  69020. }
  69021. return plugin;
  69022. };
  69023. // Public functions
  69024. SceneLoader.GetPluginForExtension = function (extension) {
  69025. return SceneLoader._getPluginForExtension(extension).plugin;
  69026. };
  69027. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  69028. return !!SceneLoader._registeredPlugins[extension];
  69029. };
  69030. SceneLoader.RegisterPlugin = function (plugin) {
  69031. if (typeof plugin.extensions === "string") {
  69032. var extension = plugin.extensions;
  69033. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69034. plugin: plugin,
  69035. isBinary: false
  69036. };
  69037. }
  69038. else {
  69039. var extensions = plugin.extensions;
  69040. Object.keys(extensions).forEach(function (extension) {
  69041. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  69042. plugin: plugin,
  69043. isBinary: extensions[extension].isBinary
  69044. };
  69045. });
  69046. }
  69047. };
  69048. /**
  69049. * Import meshes into a scene
  69050. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69051. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69052. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69053. * @param scene the instance of BABYLON.Scene to append to
  69054. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  69055. * @param onProgress a callback with a progress event for each file being loaded
  69056. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69057. * @param pluginExtension the extension used to determine the plugin
  69058. * @returns The loaded plugin
  69059. */
  69060. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69061. if (sceneFilename === void 0) { sceneFilename = ""; }
  69062. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69063. if (onSuccess === void 0) { onSuccess = null; }
  69064. if (onProgress === void 0) { onProgress = null; }
  69065. if (onError === void 0) { onError = null; }
  69066. if (pluginExtension === void 0) { pluginExtension = null; }
  69067. if (!scene) {
  69068. BABYLON.Tools.Error("No scene available to import mesh to");
  69069. return null;
  69070. }
  69071. if (!sceneFilename) {
  69072. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69073. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69074. }
  69075. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69076. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69077. return null;
  69078. }
  69079. var loadingToken = {};
  69080. scene._addPendingData(loadingToken);
  69081. var disposeHandler = function () {
  69082. scene._removePendingData(loadingToken);
  69083. };
  69084. var errorHandler = function (message, exception) {
  69085. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  69086. if (onError) {
  69087. onError(scene, errorMessage, exception);
  69088. }
  69089. else {
  69090. BABYLON.Tools.Error(errorMessage);
  69091. // should the exception be thrown?
  69092. }
  69093. disposeHandler();
  69094. };
  69095. var progressHandler = onProgress ? function (event) {
  69096. try {
  69097. onProgress(event);
  69098. }
  69099. catch (e) {
  69100. errorHandler("Error in onProgress callback", e);
  69101. }
  69102. } : undefined;
  69103. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  69104. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  69105. if (onSuccess) {
  69106. try {
  69107. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  69108. }
  69109. catch (e) {
  69110. errorHandler("Error in onSuccess callback", e);
  69111. }
  69112. }
  69113. scene._removePendingData(loadingToken);
  69114. };
  69115. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69116. if (plugin.rewriteRootURL) {
  69117. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  69118. }
  69119. if (sceneFilename === "") {
  69120. if (sceneFilename === "") {
  69121. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69122. }
  69123. }
  69124. if (plugin.importMesh) {
  69125. var syncedPlugin = plugin;
  69126. var meshes = new Array();
  69127. var particleSystems = new Array();
  69128. var skeletons = new Array();
  69129. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  69130. return;
  69131. }
  69132. scene.loadingPluginName = plugin.name;
  69133. successHandler(meshes, particleSystems, skeletons, []);
  69134. }
  69135. else {
  69136. var asyncedPlugin = plugin;
  69137. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  69138. scene.loadingPluginName = plugin.name;
  69139. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  69140. }).catch(function (error) {
  69141. errorHandler(error.message, error);
  69142. });
  69143. }
  69144. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69145. };
  69146. /**
  69147. * Import meshes into a scene
  69148. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  69149. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69150. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69151. * @param scene the instance of BABYLON.Scene to append to
  69152. * @param onProgress a callback with a progress event for each file being loaded
  69153. * @param pluginExtension the extension used to determine the plugin
  69154. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  69155. */
  69156. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69157. if (sceneFilename === void 0) { sceneFilename = ""; }
  69158. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69159. if (onProgress === void 0) { onProgress = null; }
  69160. if (pluginExtension === void 0) { pluginExtension = null; }
  69161. return new Promise(function (resolve, reject) {
  69162. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  69163. resolve({
  69164. meshes: meshes,
  69165. particleSystems: particleSystems,
  69166. skeletons: skeletons,
  69167. animationGroups: animationGroups
  69168. });
  69169. }, onProgress, function (scene, message, exception) {
  69170. reject(exception || new Error(message));
  69171. }, pluginExtension);
  69172. });
  69173. };
  69174. /**
  69175. * Load a scene
  69176. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69177. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69178. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69179. * @param onSuccess a callback with the scene when import succeeds
  69180. * @param onProgress a callback with a progress event for each file being loaded
  69181. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69182. * @param pluginExtension the extension used to determine the plugin
  69183. * @returns The loaded plugin
  69184. */
  69185. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  69186. if (onSuccess === void 0) { onSuccess = null; }
  69187. if (onProgress === void 0) { onProgress = null; }
  69188. if (onError === void 0) { onError = null; }
  69189. if (pluginExtension === void 0) { pluginExtension = null; }
  69190. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  69191. };
  69192. /**
  69193. * Load a scene
  69194. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69195. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69196. * @param engine is the instance of BABYLON.Engine to use to create the scene
  69197. * @param onProgress a callback with a progress event for each file being loaded
  69198. * @param pluginExtension the extension used to determine the plugin
  69199. * @returns The loaded scene
  69200. */
  69201. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  69202. if (onProgress === void 0) { onProgress = null; }
  69203. if (pluginExtension === void 0) { pluginExtension = null; }
  69204. return new Promise(function (resolve, reject) {
  69205. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  69206. resolve(scene);
  69207. }, onProgress, function (scene, message, exception) {
  69208. reject(exception || new Error(message));
  69209. }, pluginExtension);
  69210. });
  69211. };
  69212. /**
  69213. * Append a scene
  69214. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69215. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69216. * @param scene is the instance of BABYLON.Scene to append to
  69217. * @param onSuccess a callback with the scene when import succeeds
  69218. * @param onProgress a callback with a progress event for each file being loaded
  69219. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69220. * @param pluginExtension the extension used to determine the plugin
  69221. * @returns The loaded plugin
  69222. */
  69223. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69224. if (sceneFilename === void 0) { sceneFilename = ""; }
  69225. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69226. if (onSuccess === void 0) { onSuccess = null; }
  69227. if (onProgress === void 0) { onProgress = null; }
  69228. if (onError === void 0) { onError = null; }
  69229. if (pluginExtension === void 0) { pluginExtension = null; }
  69230. if (!scene) {
  69231. BABYLON.Tools.Error("No scene available to append to");
  69232. return null;
  69233. }
  69234. if (!sceneFilename) {
  69235. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69236. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69237. }
  69238. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69239. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69240. return null;
  69241. }
  69242. if (SceneLoader.ShowLoadingScreen) {
  69243. scene.getEngine().displayLoadingUI();
  69244. }
  69245. var loadingToken = {};
  69246. scene._addPendingData(loadingToken);
  69247. var disposeHandler = function () {
  69248. scene._removePendingData(loadingToken);
  69249. scene.getEngine().hideLoadingUI();
  69250. };
  69251. var errorHandler = function (message, exception) {
  69252. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69253. if (onError) {
  69254. onError(scene, errorMessage, exception);
  69255. }
  69256. else {
  69257. BABYLON.Tools.Error(errorMessage);
  69258. // should the exception be thrown?
  69259. }
  69260. disposeHandler();
  69261. };
  69262. var progressHandler = onProgress ? function (event) {
  69263. try {
  69264. onProgress(event);
  69265. }
  69266. catch (e) {
  69267. errorHandler("Error in onProgress callback", e);
  69268. }
  69269. } : undefined;
  69270. var successHandler = function () {
  69271. if (onSuccess) {
  69272. try {
  69273. onSuccess(scene);
  69274. }
  69275. catch (e) {
  69276. errorHandler("Error in onSuccess callback", e);
  69277. }
  69278. }
  69279. scene._removePendingData(loadingToken);
  69280. };
  69281. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69282. if (sceneFilename === "") {
  69283. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  69284. }
  69285. if (plugin.load) {
  69286. var syncedPlugin = plugin;
  69287. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  69288. return;
  69289. }
  69290. scene.loadingPluginName = plugin.name;
  69291. successHandler();
  69292. }
  69293. else {
  69294. var asyncedPlugin = plugin;
  69295. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  69296. scene.loadingPluginName = plugin.name;
  69297. successHandler();
  69298. }).catch(function (error) {
  69299. errorHandler(error.message, error);
  69300. });
  69301. }
  69302. if (SceneLoader.ShowLoadingScreen) {
  69303. scene.executeWhenReady(function () {
  69304. scene.getEngine().hideLoadingUI();
  69305. });
  69306. }
  69307. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69308. };
  69309. /**
  69310. * Append a scene
  69311. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69312. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69313. * @param scene is the instance of BABYLON.Scene to append to
  69314. * @param onProgress a callback with a progress event for each file being loaded
  69315. * @param pluginExtension the extension used to determine the plugin
  69316. * @returns The given scene
  69317. */
  69318. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69319. if (sceneFilename === void 0) { sceneFilename = ""; }
  69320. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69321. if (onProgress === void 0) { onProgress = null; }
  69322. if (pluginExtension === void 0) { pluginExtension = null; }
  69323. return new Promise(function (resolve, reject) {
  69324. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  69325. resolve(scene);
  69326. }, onProgress, function (scene, message, exception) {
  69327. reject(exception || new Error(message));
  69328. }, pluginExtension);
  69329. });
  69330. };
  69331. /**
  69332. * Load a scene into an asset container
  69333. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69334. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69335. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  69336. * @param onSuccess a callback with the scene when import succeeds
  69337. * @param onProgress a callback with a progress event for each file being loaded
  69338. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  69339. * @param pluginExtension the extension used to determine the plugin
  69340. * @returns The loaded plugin
  69341. */
  69342. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  69343. if (sceneFilename === void 0) { sceneFilename = ""; }
  69344. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69345. if (onSuccess === void 0) { onSuccess = null; }
  69346. if (onProgress === void 0) { onProgress = null; }
  69347. if (onError === void 0) { onError = null; }
  69348. if (pluginExtension === void 0) { pluginExtension = null; }
  69349. if (!scene) {
  69350. BABYLON.Tools.Error("No scene available to load asset container to");
  69351. return null;
  69352. }
  69353. if (!sceneFilename) {
  69354. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  69355. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  69356. }
  69357. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  69358. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  69359. return null;
  69360. }
  69361. var loadingToken = {};
  69362. scene._addPendingData(loadingToken);
  69363. var disposeHandler = function () {
  69364. scene._removePendingData(loadingToken);
  69365. };
  69366. var errorHandler = function (message, exception) {
  69367. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  69368. if (onError) {
  69369. onError(scene, errorMessage, exception);
  69370. }
  69371. else {
  69372. BABYLON.Tools.Error(errorMessage);
  69373. // should the exception be thrown?
  69374. }
  69375. disposeHandler();
  69376. };
  69377. var progressHandler = onProgress ? function (event) {
  69378. try {
  69379. onProgress(event);
  69380. }
  69381. catch (e) {
  69382. errorHandler("Error in onProgress callback", e);
  69383. }
  69384. } : undefined;
  69385. var successHandler = function (assets) {
  69386. if (onSuccess) {
  69387. try {
  69388. onSuccess(assets);
  69389. }
  69390. catch (e) {
  69391. errorHandler("Error in onSuccess callback", e);
  69392. }
  69393. }
  69394. scene._removePendingData(loadingToken);
  69395. };
  69396. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  69397. if (plugin.loadAssetContainer) {
  69398. var syncedPlugin = plugin;
  69399. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  69400. if (!assetContainer) {
  69401. return;
  69402. }
  69403. scene.loadingPluginName = plugin.name;
  69404. successHandler(assetContainer);
  69405. }
  69406. else if (plugin.loadAssetContainerAsync) {
  69407. var asyncedPlugin = plugin;
  69408. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  69409. scene.loadingPluginName = plugin.name;
  69410. successHandler(assetContainer);
  69411. }).catch(function (error) {
  69412. errorHandler(error.message, error);
  69413. });
  69414. }
  69415. else {
  69416. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  69417. }
  69418. if (SceneLoader.ShowLoadingScreen) {
  69419. scene.executeWhenReady(function () {
  69420. scene.getEngine().hideLoadingUI();
  69421. });
  69422. }
  69423. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  69424. };
  69425. /**
  69426. * Load a scene into an asset container
  69427. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  69428. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  69429. * @param scene is the instance of BABYLON.Scene to append to
  69430. * @param onProgress a callback with a progress event for each file being loaded
  69431. * @param pluginExtension the extension used to determine the plugin
  69432. * @returns The loaded asset container
  69433. */
  69434. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  69435. if (sceneFilename === void 0) { sceneFilename = ""; }
  69436. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  69437. if (onProgress === void 0) { onProgress = null; }
  69438. if (pluginExtension === void 0) { pluginExtension = null; }
  69439. return new Promise(function (resolve, reject) {
  69440. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  69441. resolve(assetContainer);
  69442. }, onProgress, function (scene, message, exception) {
  69443. reject(exception || new Error(message));
  69444. }, pluginExtension);
  69445. });
  69446. };
  69447. // Flags
  69448. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  69449. SceneLoader._ShowLoadingScreen = true;
  69450. SceneLoader._CleanBoneMatrixWeights = false;
  69451. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  69452. // Members
  69453. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  69454. SceneLoader._registeredPlugins = {};
  69455. return SceneLoader;
  69456. }());
  69457. BABYLON.SceneLoader = SceneLoader;
  69458. ;
  69459. })(BABYLON || (BABYLON = {}));
  69460. //# sourceMappingURL=babylon.sceneLoader.js.map
  69461. var BABYLON;
  69462. (function (BABYLON) {
  69463. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  69464. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69465. var parsedMaterial = parsedData.materials[index];
  69466. if (parsedMaterial.id === id) {
  69467. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69468. }
  69469. }
  69470. return null;
  69471. };
  69472. var isDescendantOf = function (mesh, names, hierarchyIds) {
  69473. for (var i in names) {
  69474. if (mesh.name === names[i]) {
  69475. hierarchyIds.push(mesh.id);
  69476. return true;
  69477. }
  69478. }
  69479. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  69480. hierarchyIds.push(mesh.id);
  69481. return true;
  69482. }
  69483. return false;
  69484. };
  69485. var logOperation = function (operation, producer) {
  69486. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  69487. };
  69488. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  69489. if (addToScene === void 0) { addToScene = false; }
  69490. var container = new BABYLON.AssetContainer(scene);
  69491. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69492. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69493. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69494. // and avoid problems with multiple concurrent .babylon loads.
  69495. var log = "importScene has failed JSON parse";
  69496. try {
  69497. var parsedData = JSON.parse(data);
  69498. log = "";
  69499. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69500. var index;
  69501. var cache;
  69502. // Lights
  69503. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  69504. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  69505. var parsedLight = parsedData.lights[index];
  69506. var light = BABYLON.Light.Parse(parsedLight, scene);
  69507. if (light) {
  69508. container.lights.push(light);
  69509. log += (index === 0 ? "\n\tLights:" : "");
  69510. log += "\n\t\t" + light.toString(fullDetails);
  69511. }
  69512. }
  69513. }
  69514. // Animations
  69515. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  69516. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  69517. var parsedAnimation = parsedData.animations[index];
  69518. var animation = BABYLON.Animation.Parse(parsedAnimation);
  69519. scene.animations.push(animation);
  69520. container.animations.push(animation);
  69521. log += (index === 0 ? "\n\tAnimations:" : "");
  69522. log += "\n\t\t" + animation.toString(fullDetails);
  69523. }
  69524. }
  69525. // Materials
  69526. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  69527. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  69528. var parsedMaterial = parsedData.materials[index];
  69529. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  69530. container.materials.push(mat);
  69531. log += (index === 0 ? "\n\tMaterials:" : "");
  69532. log += "\n\t\t" + mat.toString(fullDetails);
  69533. }
  69534. }
  69535. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69536. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  69537. var parsedMultiMaterial = parsedData.multiMaterials[index];
  69538. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69539. container.multiMaterials.push(mmat);
  69540. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  69541. log += "\n\t\t" + mmat.toString(fullDetails);
  69542. }
  69543. }
  69544. // Morph targets
  69545. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69546. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69547. var managerData = _a[_i];
  69548. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  69549. }
  69550. }
  69551. // Skeletons
  69552. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69553. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  69554. var parsedSkeleton = parsedData.skeletons[index];
  69555. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69556. container.skeletons.push(skeleton);
  69557. log += (index === 0 ? "\n\tSkeletons:" : "");
  69558. log += "\n\t\t" + skeleton.toString(fullDetails);
  69559. }
  69560. }
  69561. // Geometries
  69562. var geometries = parsedData.geometries;
  69563. if (geometries !== undefined && geometries !== null) {
  69564. var addedGeometry = new Array();
  69565. // Boxes
  69566. var boxes = geometries.boxes;
  69567. if (boxes !== undefined && boxes !== null) {
  69568. for (index = 0, cache = boxes.length; index < cache; index++) {
  69569. var parsedBox = boxes[index];
  69570. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  69571. }
  69572. }
  69573. // Spheres
  69574. var spheres = geometries.spheres;
  69575. if (spheres !== undefined && spheres !== null) {
  69576. for (index = 0, cache = spheres.length; index < cache; index++) {
  69577. var parsedSphere = spheres[index];
  69578. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  69579. }
  69580. }
  69581. // Cylinders
  69582. var cylinders = geometries.cylinders;
  69583. if (cylinders !== undefined && cylinders !== null) {
  69584. for (index = 0, cache = cylinders.length; index < cache; index++) {
  69585. var parsedCylinder = cylinders[index];
  69586. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  69587. }
  69588. }
  69589. // Toruses
  69590. var toruses = geometries.toruses;
  69591. if (toruses !== undefined && toruses !== null) {
  69592. for (index = 0, cache = toruses.length; index < cache; index++) {
  69593. var parsedTorus = toruses[index];
  69594. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  69595. }
  69596. }
  69597. // Grounds
  69598. var grounds = geometries.grounds;
  69599. if (grounds !== undefined && grounds !== null) {
  69600. for (index = 0, cache = grounds.length; index < cache; index++) {
  69601. var parsedGround = grounds[index];
  69602. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  69603. }
  69604. }
  69605. // Planes
  69606. var planes = geometries.planes;
  69607. if (planes !== undefined && planes !== null) {
  69608. for (index = 0, cache = planes.length; index < cache; index++) {
  69609. var parsedPlane = planes[index];
  69610. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  69611. }
  69612. }
  69613. // TorusKnots
  69614. var torusKnots = geometries.torusKnots;
  69615. if (torusKnots !== undefined && torusKnots !== null) {
  69616. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  69617. var parsedTorusKnot = torusKnots[index];
  69618. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  69619. }
  69620. }
  69621. // VertexData
  69622. var vertexData = geometries.vertexData;
  69623. if (vertexData !== undefined && vertexData !== null) {
  69624. for (index = 0, cache = vertexData.length; index < cache; index++) {
  69625. var parsedVertexData = vertexData[index];
  69626. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  69627. }
  69628. }
  69629. addedGeometry.forEach(function (g) {
  69630. if (g) {
  69631. container.geometries.push(g);
  69632. }
  69633. });
  69634. }
  69635. // Transform nodes
  69636. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  69637. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  69638. var parsedTransformNode = parsedData.transformNodes[index];
  69639. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  69640. container.transformNodes.push(node);
  69641. }
  69642. }
  69643. // Meshes
  69644. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69645. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69646. var parsedMesh = parsedData.meshes[index];
  69647. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69648. container.meshes.push(mesh);
  69649. log += (index === 0 ? "\n\tMeshes:" : "");
  69650. log += "\n\t\t" + mesh.toString(fullDetails);
  69651. }
  69652. }
  69653. // Cameras
  69654. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  69655. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  69656. var parsedCamera = parsedData.cameras[index];
  69657. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  69658. container.cameras.push(camera);
  69659. log += (index === 0 ? "\n\tCameras:" : "");
  69660. log += "\n\t\t" + camera.toString(fullDetails);
  69661. }
  69662. }
  69663. // Browsing all the graph to connect the dots
  69664. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  69665. var camera = scene.cameras[index];
  69666. if (camera._waitingParentId) {
  69667. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  69668. camera._waitingParentId = null;
  69669. }
  69670. }
  69671. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69672. var light_1 = scene.lights[index];
  69673. if (light_1 && light_1._waitingParentId) {
  69674. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  69675. light_1._waitingParentId = null;
  69676. }
  69677. }
  69678. // Sounds
  69679. // TODO: add sound
  69680. var loadedSounds = [];
  69681. var loadedSound;
  69682. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  69683. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  69684. var parsedSound = parsedData.sounds[index];
  69685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69686. if (!parsedSound.url)
  69687. parsedSound.url = parsedSound.name;
  69688. if (!loadedSounds[parsedSound.url]) {
  69689. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  69690. loadedSounds[parsedSound.url] = loadedSound;
  69691. container.sounds.push(loadedSound);
  69692. }
  69693. else {
  69694. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  69695. }
  69696. }
  69697. else {
  69698. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  69699. }
  69700. }
  69701. }
  69702. loadedSounds = [];
  69703. // Connect parents & children and parse actions
  69704. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  69705. var transformNode = scene.transformNodes[index];
  69706. if (transformNode._waitingParentId) {
  69707. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  69708. transformNode._waitingParentId = null;
  69709. }
  69710. }
  69711. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69712. var mesh = scene.meshes[index];
  69713. if (mesh._waitingParentId) {
  69714. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  69715. mesh._waitingParentId = null;
  69716. }
  69717. if (mesh._waitingActions) {
  69718. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  69719. mesh._waitingActions = null;
  69720. }
  69721. }
  69722. // freeze world matrix application
  69723. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69724. var currentMesh = scene.meshes[index];
  69725. if (currentMesh._waitingFreezeWorldMatrix) {
  69726. currentMesh.freezeWorldMatrix();
  69727. currentMesh._waitingFreezeWorldMatrix = null;
  69728. }
  69729. else {
  69730. currentMesh.computeWorldMatrix(true);
  69731. }
  69732. }
  69733. // Shadows
  69734. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  69735. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  69736. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  69737. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  69738. // SG would be available on their associated lights
  69739. }
  69740. }
  69741. // Lights exclusions / inclusions
  69742. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  69743. var light_2 = scene.lights[index];
  69744. // Excluded check
  69745. if (light_2._excludedMeshesIds.length > 0) {
  69746. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  69747. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  69748. if (excludedMesh) {
  69749. light_2.excludedMeshes.push(excludedMesh);
  69750. }
  69751. }
  69752. light_2._excludedMeshesIds = [];
  69753. }
  69754. // Included check
  69755. if (light_2._includedOnlyMeshesIds.length > 0) {
  69756. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  69757. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  69758. if (includedOnlyMesh) {
  69759. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  69760. }
  69761. }
  69762. light_2._includedOnlyMeshesIds = [];
  69763. }
  69764. }
  69765. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  69766. // Actions (scene)
  69767. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  69768. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  69769. }
  69770. if (!addToScene) {
  69771. container.removeAllFromScene();
  69772. }
  69773. }
  69774. catch (err) {
  69775. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  69776. if (onError) {
  69777. onError(msg, err);
  69778. }
  69779. else {
  69780. BABYLON.Tools.Log(msg);
  69781. throw err;
  69782. }
  69783. }
  69784. finally {
  69785. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69786. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69787. }
  69788. }
  69789. return container;
  69790. };
  69791. BABYLON.SceneLoader.RegisterPlugin({
  69792. name: "babylon.js",
  69793. extensions: ".babylon",
  69794. canDirectLoad: function (data) {
  69795. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  69796. return true;
  69797. }
  69798. return false;
  69799. },
  69800. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  69801. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69802. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69803. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69804. // and avoid problems with multiple concurrent .babylon loads.
  69805. var log = "importMesh has failed JSON parse";
  69806. try {
  69807. var parsedData = JSON.parse(data);
  69808. log = "";
  69809. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  69810. if (!meshesNames) {
  69811. meshesNames = null;
  69812. }
  69813. else if (!Array.isArray(meshesNames)) {
  69814. meshesNames = [meshesNames];
  69815. }
  69816. var hierarchyIds = new Array();
  69817. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  69818. var loadedSkeletonsIds = [];
  69819. var loadedMaterialsIds = [];
  69820. var index;
  69821. var cache;
  69822. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  69823. var parsedMesh = parsedData.meshes[index];
  69824. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  69825. if (meshesNames !== null) {
  69826. // Remove found mesh name from list.
  69827. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  69828. }
  69829. //Geometry?
  69830. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  69831. //does the file contain geometries?
  69832. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  69833. //find the correct geometry and add it to the scene
  69834. var found = false;
  69835. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  69836. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  69837. return;
  69838. }
  69839. else {
  69840. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  69841. if (parsedGeometryData.id === parsedMesh.geometryId) {
  69842. switch (geometryType) {
  69843. case "boxes":
  69844. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  69845. break;
  69846. case "spheres":
  69847. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  69848. break;
  69849. case "cylinders":
  69850. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  69851. break;
  69852. case "toruses":
  69853. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  69854. break;
  69855. case "grounds":
  69856. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  69857. break;
  69858. case "planes":
  69859. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  69860. break;
  69861. case "torusKnots":
  69862. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  69863. break;
  69864. case "vertexData":
  69865. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  69866. break;
  69867. }
  69868. found = true;
  69869. }
  69870. });
  69871. }
  69872. });
  69873. if (found === false) {
  69874. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  69875. }
  69876. }
  69877. }
  69878. // Material ?
  69879. if (parsedMesh.materialId) {
  69880. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  69881. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  69882. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  69883. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  69884. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  69885. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  69886. var subMatId = parsedMultiMaterial.materials[matIndex];
  69887. loadedMaterialsIds.push(subMatId);
  69888. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  69889. if (mat) {
  69890. log += "\n\tMaterial " + mat.toString(fullDetails);
  69891. }
  69892. }
  69893. loadedMaterialsIds.push(parsedMultiMaterial.id);
  69894. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  69895. if (mmat) {
  69896. materialFound = true;
  69897. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  69898. }
  69899. break;
  69900. }
  69901. }
  69902. }
  69903. if (materialFound === false) {
  69904. loadedMaterialsIds.push(parsedMesh.materialId);
  69905. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  69906. if (!mat) {
  69907. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  69908. }
  69909. else {
  69910. log += "\n\tMaterial " + mat.toString(fullDetails);
  69911. }
  69912. }
  69913. }
  69914. // Skeleton ?
  69915. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  69916. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  69917. if (skeletonAlreadyLoaded === false) {
  69918. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  69919. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  69920. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  69921. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  69922. skeletons.push(skeleton);
  69923. loadedSkeletonsIds.push(parsedSkeleton.id);
  69924. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  69925. }
  69926. }
  69927. }
  69928. }
  69929. // Morph targets ?
  69930. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  69931. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  69932. var managerData = _a[_i];
  69933. BABYLON.MorphTargetManager.Parse(managerData, scene);
  69934. }
  69935. }
  69936. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  69937. meshes.push(mesh);
  69938. log += "\n\tMesh " + mesh.toString(fullDetails);
  69939. }
  69940. }
  69941. // Connecting parents
  69942. var currentMesh;
  69943. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69944. currentMesh = scene.meshes[index];
  69945. if (currentMesh._waitingParentId) {
  69946. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  69947. currentMesh._waitingParentId = null;
  69948. }
  69949. }
  69950. // freeze and compute world matrix application
  69951. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  69952. currentMesh = scene.meshes[index];
  69953. if (currentMesh._waitingFreezeWorldMatrix) {
  69954. currentMesh.freezeWorldMatrix();
  69955. currentMesh._waitingFreezeWorldMatrix = null;
  69956. }
  69957. else {
  69958. currentMesh.computeWorldMatrix(true);
  69959. }
  69960. }
  69961. }
  69962. // Particles
  69963. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  69964. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  69965. if (parser) {
  69966. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  69967. var parsedParticleSystem = parsedData.particleSystems[index];
  69968. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  69969. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  69970. }
  69971. }
  69972. }
  69973. }
  69974. return true;
  69975. }
  69976. catch (err) {
  69977. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  69978. if (onError) {
  69979. onError(msg, err);
  69980. }
  69981. else {
  69982. BABYLON.Tools.Log(msg);
  69983. throw err;
  69984. }
  69985. }
  69986. finally {
  69987. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  69988. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  69989. }
  69990. }
  69991. return false;
  69992. },
  69993. load: function (scene, data, rootUrl, onError) {
  69994. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  69995. // when SceneLoader.debugLogging = true (default), or exception encountered.
  69996. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  69997. // and avoid problems with multiple concurrent .babylon loads.
  69998. var log = "importScene has failed JSON parse";
  69999. try {
  70000. var parsedData = JSON.parse(data);
  70001. log = "";
  70002. // Scene
  70003. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  70004. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  70005. }
  70006. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  70007. scene.autoClear = parsedData.autoClear;
  70008. }
  70009. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  70010. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  70011. }
  70012. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  70013. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  70014. }
  70015. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  70016. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  70017. }
  70018. // Fog
  70019. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  70020. scene.fogMode = parsedData.fogMode;
  70021. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  70022. scene.fogStart = parsedData.fogStart;
  70023. scene.fogEnd = parsedData.fogEnd;
  70024. scene.fogDensity = parsedData.fogDensity;
  70025. log += "\tFog mode for scene: ";
  70026. switch (scene.fogMode) {
  70027. // getters not compiling, so using hardcoded
  70028. case 1:
  70029. log += "exp\n";
  70030. break;
  70031. case 2:
  70032. log += "exp2\n";
  70033. break;
  70034. case 3:
  70035. log += "linear\n";
  70036. break;
  70037. }
  70038. }
  70039. //Physics
  70040. if (parsedData.physicsEnabled) {
  70041. var physicsPlugin;
  70042. if (parsedData.physicsEngine === "cannon") {
  70043. physicsPlugin = new BABYLON.CannonJSPlugin();
  70044. }
  70045. else if (parsedData.physicsEngine === "oimo") {
  70046. physicsPlugin = new BABYLON.OimoJSPlugin();
  70047. }
  70048. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  70049. //else - default engine, which is currently oimo
  70050. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  70051. scene.enablePhysics(physicsGravity, physicsPlugin);
  70052. }
  70053. // Metadata
  70054. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  70055. scene.metadata = parsedData.metadata;
  70056. }
  70057. //collisions, if defined. otherwise, default is true
  70058. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  70059. scene.collisionsEnabled = parsedData.collisionsEnabled;
  70060. }
  70061. scene.workerCollisions = !!parsedData.workerCollisions;
  70062. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  70063. if (!container) {
  70064. return false;
  70065. }
  70066. if (parsedData.autoAnimate) {
  70067. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  70068. }
  70069. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  70070. scene.setActiveCameraByID(parsedData.activeCameraID);
  70071. }
  70072. // Environment texture
  70073. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  70074. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  70075. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  70076. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  70077. if (parsedData.environmentTextureRotationY) {
  70078. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  70079. }
  70080. scene.environmentTexture = hdrTexture;
  70081. }
  70082. else {
  70083. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  70084. if (parsedData.environmentTextureRotationY) {
  70085. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  70086. }
  70087. scene.environmentTexture = cubeTexture;
  70088. }
  70089. if (parsedData.createDefaultSkybox === true) {
  70090. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  70091. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  70092. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  70093. }
  70094. }
  70095. // Finish
  70096. return true;
  70097. }
  70098. catch (err) {
  70099. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  70100. if (onError) {
  70101. onError(msg, err);
  70102. }
  70103. else {
  70104. BABYLON.Tools.Log(msg);
  70105. throw err;
  70106. }
  70107. }
  70108. finally {
  70109. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  70110. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  70111. }
  70112. }
  70113. return false;
  70114. },
  70115. loadAssetContainer: function (scene, data, rootUrl, onError) {
  70116. var container = loadAssetContainer(scene, data, rootUrl, onError);
  70117. return container;
  70118. }
  70119. });
  70120. })(BABYLON || (BABYLON = {}));
  70121. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  70122. var BABYLON;
  70123. (function (BABYLON) {
  70124. var FilesInput = /** @class */ (function () {
  70125. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  70126. this.onProcessFileCallback = function () { return true; };
  70127. this._engine = engine;
  70128. this._currentScene = scene;
  70129. this._sceneLoadedCallback = sceneLoadedCallback;
  70130. this._progressCallback = progressCallback;
  70131. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  70132. this._textureLoadingCallback = textureLoadingCallback;
  70133. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  70134. this._onReloadCallback = onReloadCallback;
  70135. this._errorCallback = errorCallback;
  70136. }
  70137. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  70138. var _this = this;
  70139. if (elementToMonitor) {
  70140. this._elementToMonitor = elementToMonitor;
  70141. this._dragEnterHandler = function (e) { _this.drag(e); };
  70142. this._dragOverHandler = function (e) { _this.drag(e); };
  70143. this._dropHandler = function (e) { _this.drop(e); };
  70144. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  70145. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  70146. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  70147. }
  70148. };
  70149. FilesInput.prototype.dispose = function () {
  70150. if (!this._elementToMonitor) {
  70151. return;
  70152. }
  70153. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  70154. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  70155. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  70156. };
  70157. FilesInput.prototype.renderFunction = function () {
  70158. if (this._additionalRenderLoopLogicCallback) {
  70159. this._additionalRenderLoopLogicCallback();
  70160. }
  70161. if (this._currentScene) {
  70162. if (this._textureLoadingCallback) {
  70163. var remaining = this._currentScene.getWaitingItemsCount();
  70164. if (remaining > 0) {
  70165. this._textureLoadingCallback(remaining);
  70166. }
  70167. }
  70168. this._currentScene.render();
  70169. }
  70170. };
  70171. FilesInput.prototype.drag = function (e) {
  70172. e.stopPropagation();
  70173. e.preventDefault();
  70174. };
  70175. FilesInput.prototype.drop = function (eventDrop) {
  70176. eventDrop.stopPropagation();
  70177. eventDrop.preventDefault();
  70178. this.loadFiles(eventDrop);
  70179. };
  70180. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  70181. var _this = this;
  70182. var reader = folder.createReader();
  70183. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  70184. reader.readEntries(function (entries) {
  70185. remaining.count += entries.length;
  70186. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  70187. var entry = entries_1[_i];
  70188. if (entry.isFile) {
  70189. entry.file(function (file) {
  70190. file.correctName = relativePath + file.name;
  70191. files.push(file);
  70192. if (--remaining.count === 0) {
  70193. callback();
  70194. }
  70195. });
  70196. }
  70197. else if (entry.isDirectory) {
  70198. _this._traverseFolder(entry, files, remaining, callback);
  70199. }
  70200. }
  70201. if (--remaining.count) {
  70202. callback();
  70203. }
  70204. });
  70205. };
  70206. FilesInput.prototype._processFiles = function (files) {
  70207. for (var i = 0; i < files.length; i++) {
  70208. var name = files[i].correctName.toLowerCase();
  70209. var extension = name.split('.').pop();
  70210. if (!this.onProcessFileCallback(files[i], name, extension)) {
  70211. continue;
  70212. }
  70213. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  70214. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  70215. this._sceneFileToLoad = files[i];
  70216. }
  70217. else {
  70218. FilesInput.FilesToLoad[name] = files[i];
  70219. }
  70220. }
  70221. };
  70222. FilesInput.prototype.loadFiles = function (event) {
  70223. var _this = this;
  70224. if (this._startingProcessingFilesCallback)
  70225. this._startingProcessingFilesCallback();
  70226. // Handling data transfer via drag'n'drop
  70227. if (event && event.dataTransfer && event.dataTransfer.files) {
  70228. this._filesToLoad = event.dataTransfer.files;
  70229. }
  70230. // Handling files from input files
  70231. if (event && event.target && event.target.files) {
  70232. this._filesToLoad = event.target.files;
  70233. }
  70234. if (this._filesToLoad && this._filesToLoad.length > 0) {
  70235. var files_1 = new Array();
  70236. var folders = [];
  70237. var items = event.dataTransfer ? event.dataTransfer.items : null;
  70238. for (var i = 0; i < this._filesToLoad.length; i++) {
  70239. var fileToLoad = this._filesToLoad[i];
  70240. var name_1 = fileToLoad.name.toLowerCase();
  70241. var entry = void 0;
  70242. fileToLoad.correctName = name_1;
  70243. if (items) {
  70244. var item = items[i];
  70245. if (item.getAsEntry) {
  70246. entry = item.getAsEntry();
  70247. }
  70248. else if (item.webkitGetAsEntry) {
  70249. entry = item.webkitGetAsEntry();
  70250. }
  70251. }
  70252. if (!entry) {
  70253. files_1.push(fileToLoad);
  70254. }
  70255. else {
  70256. if (entry.isDirectory) {
  70257. folders.push(entry);
  70258. }
  70259. else {
  70260. files_1.push(fileToLoad);
  70261. }
  70262. }
  70263. }
  70264. if (folders.length === 0) {
  70265. this._processFiles(files_1);
  70266. this._processReload();
  70267. }
  70268. else {
  70269. var remaining = { count: folders.length };
  70270. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  70271. var folder = folders_1[_i];
  70272. this._traverseFolder(folder, files_1, remaining, function () {
  70273. _this._processFiles(files_1);
  70274. if (remaining.count === 0) {
  70275. _this._processReload();
  70276. }
  70277. });
  70278. }
  70279. }
  70280. }
  70281. };
  70282. FilesInput.prototype._processReload = function () {
  70283. if (this._onReloadCallback) {
  70284. this._onReloadCallback(this._sceneFileToLoad);
  70285. }
  70286. else {
  70287. this.reload();
  70288. }
  70289. };
  70290. FilesInput.prototype.reload = function () {
  70291. var _this = this;
  70292. // If a scene file has been provided
  70293. if (this._sceneFileToLoad) {
  70294. if (this._currentScene) {
  70295. if (BABYLON.Tools.errorsCount > 0) {
  70296. BABYLON.Tools.ClearLogCache();
  70297. }
  70298. this._engine.stopRenderLoop();
  70299. }
  70300. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  70301. if (_this._progressCallback) {
  70302. _this._progressCallback(progress);
  70303. }
  70304. }).then(function (scene) {
  70305. if (_this._currentScene) {
  70306. _this._currentScene.dispose();
  70307. }
  70308. _this._currentScene = scene;
  70309. if (_this._sceneLoadedCallback) {
  70310. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  70311. }
  70312. // Wait for textures and shaders to be ready
  70313. _this._currentScene.executeWhenReady(function () {
  70314. _this._engine.runRenderLoop(function () {
  70315. _this.renderFunction();
  70316. });
  70317. });
  70318. }).catch(function (error) {
  70319. if (_this._errorCallback) {
  70320. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  70321. }
  70322. });
  70323. }
  70324. else {
  70325. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  70326. }
  70327. };
  70328. FilesInput.FilesToLoad = {};
  70329. return FilesInput;
  70330. }());
  70331. BABYLON.FilesInput = FilesInput;
  70332. })(BABYLON || (BABYLON = {}));
  70333. //# sourceMappingURL=babylon.filesInput.js.map
  70334. var BABYLON;
  70335. (function (BABYLON) {
  70336. var Tags = /** @class */ (function () {
  70337. function Tags() {
  70338. }
  70339. Tags.EnableFor = function (obj) {
  70340. obj._tags = obj._tags || {};
  70341. obj.hasTags = function () {
  70342. return Tags.HasTags(obj);
  70343. };
  70344. obj.addTags = function (tagsString) {
  70345. return Tags.AddTagsTo(obj, tagsString);
  70346. };
  70347. obj.removeTags = function (tagsString) {
  70348. return Tags.RemoveTagsFrom(obj, tagsString);
  70349. };
  70350. obj.matchesTagsQuery = function (tagsQuery) {
  70351. return Tags.MatchesQuery(obj, tagsQuery);
  70352. };
  70353. };
  70354. Tags.DisableFor = function (obj) {
  70355. delete obj._tags;
  70356. delete obj.hasTags;
  70357. delete obj.addTags;
  70358. delete obj.removeTags;
  70359. delete obj.matchesTagsQuery;
  70360. };
  70361. Tags.HasTags = function (obj) {
  70362. if (!obj._tags) {
  70363. return false;
  70364. }
  70365. return !BABYLON.Tools.IsEmpty(obj._tags);
  70366. };
  70367. Tags.GetTags = function (obj, asString) {
  70368. if (asString === void 0) { asString = true; }
  70369. if (!obj._tags) {
  70370. return null;
  70371. }
  70372. if (asString) {
  70373. var tagsArray = [];
  70374. for (var tag in obj._tags) {
  70375. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  70376. tagsArray.push(tag);
  70377. }
  70378. }
  70379. return tagsArray.join(" ");
  70380. }
  70381. else {
  70382. return obj._tags;
  70383. }
  70384. };
  70385. // the tags 'true' and 'false' are reserved and cannot be used as tags
  70386. // a tag cannot start with '||', '&&', and '!'
  70387. // it cannot contain whitespaces
  70388. Tags.AddTagsTo = function (obj, tagsString) {
  70389. if (!tagsString) {
  70390. return;
  70391. }
  70392. if (typeof tagsString !== "string") {
  70393. return;
  70394. }
  70395. var tags = tagsString.split(" ");
  70396. tags.forEach(function (tag, index, array) {
  70397. Tags._AddTagTo(obj, tag);
  70398. });
  70399. };
  70400. Tags._AddTagTo = function (obj, tag) {
  70401. tag = tag.trim();
  70402. if (tag === "" || tag === "true" || tag === "false") {
  70403. return;
  70404. }
  70405. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  70406. return;
  70407. }
  70408. Tags.EnableFor(obj);
  70409. obj._tags[tag] = true;
  70410. };
  70411. Tags.RemoveTagsFrom = function (obj, tagsString) {
  70412. if (!Tags.HasTags(obj)) {
  70413. return;
  70414. }
  70415. var tags = tagsString.split(" ");
  70416. for (var t in tags) {
  70417. Tags._RemoveTagFrom(obj, tags[t]);
  70418. }
  70419. };
  70420. Tags._RemoveTagFrom = function (obj, tag) {
  70421. delete obj._tags[tag];
  70422. };
  70423. Tags.MatchesQuery = function (obj, tagsQuery) {
  70424. if (tagsQuery === undefined) {
  70425. return true;
  70426. }
  70427. if (tagsQuery === "") {
  70428. return Tags.HasTags(obj);
  70429. }
  70430. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  70431. };
  70432. return Tags;
  70433. }());
  70434. BABYLON.Tags = Tags;
  70435. })(BABYLON || (BABYLON = {}));
  70436. //# sourceMappingURL=babylon.tags.js.map
  70437. var BABYLON;
  70438. (function (BABYLON) {
  70439. /**
  70440. * Class used to evalaute queries containing `and` and `or` operators
  70441. */
  70442. var AndOrNotEvaluator = /** @class */ (function () {
  70443. function AndOrNotEvaluator() {
  70444. }
  70445. /**
  70446. * Evaluate a query
  70447. * @param query defines the query to evaluate
  70448. * @param evaluateCallback defines the callback used to filter result
  70449. * @returns true if the query matches
  70450. */
  70451. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  70452. if (!query.match(/\([^\(\)]*\)/g)) {
  70453. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  70454. }
  70455. else {
  70456. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  70457. // remove parenthesis
  70458. r = r.slice(1, r.length - 1);
  70459. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  70460. });
  70461. }
  70462. if (query === "true") {
  70463. return true;
  70464. }
  70465. if (query === "false") {
  70466. return false;
  70467. }
  70468. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  70469. };
  70470. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  70471. evaluateCallback = evaluateCallback || (function (r) {
  70472. return r === "true" ? true : false;
  70473. });
  70474. var result;
  70475. var or = parenthesisContent.split("||");
  70476. for (var i in or) {
  70477. if (or.hasOwnProperty(i)) {
  70478. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  70479. var and = ori.split("&&");
  70480. if (and.length > 1) {
  70481. for (var j = 0; j < and.length; ++j) {
  70482. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  70483. if (andj !== "true" && andj !== "false") {
  70484. if (andj[0] === "!") {
  70485. result = !evaluateCallback(andj.substring(1));
  70486. }
  70487. else {
  70488. result = evaluateCallback(andj);
  70489. }
  70490. }
  70491. else {
  70492. result = andj === "true" ? true : false;
  70493. }
  70494. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  70495. ori = "false";
  70496. break;
  70497. }
  70498. }
  70499. }
  70500. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  70501. result = true;
  70502. break;
  70503. }
  70504. // result equals false (or undefined)
  70505. if (ori !== "true" && ori !== "false") {
  70506. if (ori[0] === "!") {
  70507. result = !evaluateCallback(ori.substring(1));
  70508. }
  70509. else {
  70510. result = evaluateCallback(ori);
  70511. }
  70512. }
  70513. else {
  70514. result = ori === "true" ? true : false;
  70515. }
  70516. }
  70517. }
  70518. // the whole parenthesis scope is replaced by 'true' or 'false'
  70519. return result ? "true" : "false";
  70520. };
  70521. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  70522. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  70523. // remove whitespaces
  70524. r = r.replace(/[\s]/g, function () { return ""; });
  70525. return r.length % 2 ? "!" : "";
  70526. });
  70527. booleanString = booleanString.trim();
  70528. if (booleanString === "!true") {
  70529. booleanString = "false";
  70530. }
  70531. else if (booleanString === "!false") {
  70532. booleanString = "true";
  70533. }
  70534. return booleanString;
  70535. };
  70536. return AndOrNotEvaluator;
  70537. }());
  70538. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  70539. })(BABYLON || (BABYLON = {}));
  70540. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  70541. var BABYLON;
  70542. (function (BABYLON) {
  70543. /**
  70544. * Class used to enable access to IndexedDB
  70545. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  70546. */
  70547. var Database = /** @class */ (function () {
  70548. /**
  70549. * Creates a new Database
  70550. * @param urlToScene defines the url to load the scene
  70551. * @param callbackManifestChecked defines the callback to use when manifest is checked
  70552. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  70553. */
  70554. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  70555. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  70556. var _this = this;
  70557. // Handling various flavors of prefixed version of IndexedDB
  70558. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  70559. this.callbackManifestChecked = callbackManifestChecked;
  70560. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  70561. this.db = null;
  70562. this._enableSceneOffline = false;
  70563. this._enableTexturesOffline = false;
  70564. this.manifestVersionFound = 0;
  70565. this.mustUpdateRessources = false;
  70566. this.hasReachedQuota = false;
  70567. if (!Database.IDBStorageEnabled) {
  70568. this.callbackManifestChecked(true);
  70569. }
  70570. else {
  70571. if (disableManifestCheck) {
  70572. this._enableSceneOffline = true;
  70573. this._enableTexturesOffline = true;
  70574. this.manifestVersionFound = 1;
  70575. BABYLON.Tools.SetImmediate(function () {
  70576. _this.callbackManifestChecked(true);
  70577. });
  70578. }
  70579. else {
  70580. this._checkManifestFile();
  70581. }
  70582. }
  70583. }
  70584. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  70585. /**
  70586. * Gets a boolean indicating if scene must be saved in the database
  70587. */
  70588. get: function () {
  70589. return this._enableSceneOffline;
  70590. },
  70591. enumerable: true,
  70592. configurable: true
  70593. });
  70594. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  70595. /**
  70596. * Gets a boolean indicating if textures must be saved in the database
  70597. */
  70598. get: function () {
  70599. return this._enableTexturesOffline;
  70600. },
  70601. enumerable: true,
  70602. configurable: true
  70603. });
  70604. Database.prototype._checkManifestFile = function () {
  70605. var _this = this;
  70606. var noManifestFile = function () {
  70607. _this._enableSceneOffline = false;
  70608. _this._enableTexturesOffline = false;
  70609. _this.callbackManifestChecked(false);
  70610. };
  70611. var timeStampUsed = false;
  70612. var manifestURL = this.currentSceneUrl + ".manifest";
  70613. var xhr = new XMLHttpRequest();
  70614. if (navigator.onLine) {
  70615. // Adding a timestamp to by-pass browsers' cache
  70616. timeStampUsed = true;
  70617. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  70618. }
  70619. xhr.open("GET", manifestURL, true);
  70620. xhr.addEventListener("load", function () {
  70621. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70622. try {
  70623. var manifestFile = JSON.parse(xhr.response);
  70624. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  70625. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  70626. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  70627. _this.manifestVersionFound = manifestFile.version;
  70628. }
  70629. if (_this.callbackManifestChecked) {
  70630. _this.callbackManifestChecked(true);
  70631. }
  70632. }
  70633. catch (ex) {
  70634. noManifestFile();
  70635. }
  70636. }
  70637. else {
  70638. noManifestFile();
  70639. }
  70640. }, false);
  70641. xhr.addEventListener("error", function (event) {
  70642. if (timeStampUsed) {
  70643. timeStampUsed = false;
  70644. // Let's retry without the timeStamp
  70645. // It could fail when coupled with HTML5 Offline API
  70646. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  70647. xhr.open("GET", retryManifestURL, true);
  70648. xhr.send();
  70649. }
  70650. else {
  70651. noManifestFile();
  70652. }
  70653. }, false);
  70654. try {
  70655. xhr.send();
  70656. }
  70657. catch (ex) {
  70658. BABYLON.Tools.Error("Error on XHR send request.");
  70659. this.callbackManifestChecked(false);
  70660. }
  70661. };
  70662. /**
  70663. * Open the database and make it available
  70664. * @param successCallback defines the callback to call on success
  70665. * @param errorCallback defines the callback to call on error
  70666. */
  70667. Database.prototype.openAsync = function (successCallback, errorCallback) {
  70668. var _this = this;
  70669. var handleError = function () {
  70670. _this.isSupported = false;
  70671. if (errorCallback)
  70672. errorCallback();
  70673. };
  70674. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  70675. // Your browser doesn't support IndexedDB
  70676. this.isSupported = false;
  70677. if (errorCallback)
  70678. errorCallback();
  70679. }
  70680. else {
  70681. // If the DB hasn't been opened or created yet
  70682. if (!this.db) {
  70683. this.hasReachedQuota = false;
  70684. this.isSupported = true;
  70685. var request = this.idbFactory.open("babylonjs", 1);
  70686. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  70687. request.onerror = function (event) {
  70688. handleError();
  70689. };
  70690. // executes when a version change transaction cannot complete due to other active transactions
  70691. request.onblocked = function (event) {
  70692. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  70693. handleError();
  70694. };
  70695. // DB has been opened successfully
  70696. request.onsuccess = function (event) {
  70697. _this.db = request.result;
  70698. successCallback();
  70699. };
  70700. // Initialization of the DB. Creating Scenes & Textures stores
  70701. request.onupgradeneeded = function (event) {
  70702. _this.db = (event.target).result;
  70703. if (_this.db) {
  70704. try {
  70705. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  70706. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  70707. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  70708. }
  70709. catch (ex) {
  70710. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  70711. handleError();
  70712. }
  70713. }
  70714. };
  70715. }
  70716. // DB has already been created and opened
  70717. else {
  70718. if (successCallback)
  70719. successCallback();
  70720. }
  70721. }
  70722. };
  70723. /**
  70724. * Loads an image from the database
  70725. * @param url defines the url to load from
  70726. * @param image defines the target DOM image
  70727. */
  70728. Database.prototype.loadImageFromDB = function (url, image) {
  70729. var _this = this;
  70730. var completeURL = Database._ReturnFullUrlLocation(url);
  70731. var saveAndLoadImage = function () {
  70732. if (!_this.hasReachedQuota && _this.db !== null) {
  70733. // the texture is not yet in the DB, let's try to save it
  70734. _this._saveImageIntoDBAsync(completeURL, image);
  70735. }
  70736. // If the texture is not in the DB and we've reached the DB quota limit
  70737. // let's load it directly from the web
  70738. else {
  70739. image.src = url;
  70740. }
  70741. };
  70742. if (!this.mustUpdateRessources) {
  70743. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  70744. }
  70745. // First time we're download the images or update requested in the manifest file by a version change
  70746. else {
  70747. saveAndLoadImage();
  70748. }
  70749. };
  70750. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  70751. if (this.isSupported && this.db !== null) {
  70752. var texture;
  70753. var transaction = this.db.transaction(["textures"]);
  70754. transaction.onabort = function (event) {
  70755. image.src = url;
  70756. };
  70757. transaction.oncomplete = function (event) {
  70758. var blobTextureURL;
  70759. if (texture) {
  70760. var URL = window.URL || window.webkitURL;
  70761. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  70762. image.onerror = function () {
  70763. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  70764. image.src = url;
  70765. };
  70766. image.src = blobTextureURL;
  70767. }
  70768. else {
  70769. notInDBCallback();
  70770. }
  70771. };
  70772. var getRequest = transaction.objectStore("textures").get(url);
  70773. getRequest.onsuccess = function (event) {
  70774. texture = (event.target).result;
  70775. };
  70776. getRequest.onerror = function (event) {
  70777. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  70778. image.src = url;
  70779. };
  70780. }
  70781. else {
  70782. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70783. image.src = url;
  70784. }
  70785. };
  70786. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  70787. var _this = this;
  70788. if (this.isSupported) {
  70789. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  70790. var generateBlobUrl = function () {
  70791. var blobTextureURL;
  70792. if (blob) {
  70793. var URL = window.URL || window.webkitURL;
  70794. try {
  70795. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  70796. }
  70797. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  70798. catch (ex) {
  70799. blobTextureURL = URL.createObjectURL(blob);
  70800. }
  70801. }
  70802. if (blobTextureURL) {
  70803. image.src = blobTextureURL;
  70804. }
  70805. };
  70806. if (Database.IsUASupportingBlobStorage) { // Create XHR
  70807. var xhr = new XMLHttpRequest(), blob;
  70808. xhr.open("GET", url, true);
  70809. xhr.responseType = "blob";
  70810. xhr.addEventListener("load", function () {
  70811. if (xhr.status === 200 && _this.db) {
  70812. // Blob as response (XHR2)
  70813. blob = xhr.response;
  70814. var transaction = _this.db.transaction(["textures"], "readwrite");
  70815. // the transaction could abort because of a QuotaExceededError error
  70816. transaction.onabort = function (event) {
  70817. try {
  70818. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70819. var srcElement = (event.srcElement || event.target);
  70820. var error = srcElement.error;
  70821. if (error && error.name === "QuotaExceededError") {
  70822. _this.hasReachedQuota = true;
  70823. }
  70824. }
  70825. catch (ex) { }
  70826. generateBlobUrl();
  70827. };
  70828. transaction.oncomplete = function (event) {
  70829. generateBlobUrl();
  70830. };
  70831. var newTexture = { textureUrl: url, data: blob };
  70832. try {
  70833. // Put the blob into the dabase
  70834. var addRequest = transaction.objectStore("textures").put(newTexture);
  70835. addRequest.onsuccess = function (event) {
  70836. };
  70837. addRequest.onerror = function (event) {
  70838. generateBlobUrl();
  70839. };
  70840. }
  70841. catch (ex) {
  70842. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  70843. if (ex.code === 25) {
  70844. Database.IsUASupportingBlobStorage = false;
  70845. }
  70846. image.src = url;
  70847. }
  70848. }
  70849. else {
  70850. image.src = url;
  70851. }
  70852. }, false);
  70853. xhr.addEventListener("error", function (event) {
  70854. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  70855. image.src = url;
  70856. }, false);
  70857. xhr.send();
  70858. }
  70859. else {
  70860. image.src = url;
  70861. }
  70862. }
  70863. else {
  70864. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70865. image.src = url;
  70866. }
  70867. };
  70868. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  70869. var _this = this;
  70870. var updateVersion = function () {
  70871. // the version is not yet in the DB or we need to update it
  70872. _this._saveVersionIntoDBAsync(url, versionLoaded);
  70873. };
  70874. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  70875. };
  70876. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  70877. var _this = this;
  70878. if (this.isSupported && this.db) {
  70879. var version;
  70880. try {
  70881. var transaction = this.db.transaction(["versions"]);
  70882. transaction.oncomplete = function (event) {
  70883. if (version) {
  70884. // If the version in the JSON file is different from the version in DB
  70885. if (_this.manifestVersionFound !== version.data) {
  70886. _this.mustUpdateRessources = true;
  70887. updateInDBCallback();
  70888. }
  70889. else {
  70890. callback(version.data);
  70891. }
  70892. }
  70893. // version was not found in DB
  70894. else {
  70895. _this.mustUpdateRessources = true;
  70896. updateInDBCallback();
  70897. }
  70898. };
  70899. transaction.onabort = function (event) {
  70900. callback(-1);
  70901. };
  70902. var getRequest = transaction.objectStore("versions").get(url);
  70903. getRequest.onsuccess = function (event) {
  70904. version = (event.target).result;
  70905. };
  70906. getRequest.onerror = function (event) {
  70907. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  70908. callback(-1);
  70909. };
  70910. }
  70911. catch (ex) {
  70912. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  70913. callback(-1);
  70914. }
  70915. }
  70916. else {
  70917. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70918. callback(-1);
  70919. }
  70920. };
  70921. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  70922. var _this = this;
  70923. if (this.isSupported && !this.hasReachedQuota && this.db) {
  70924. try {
  70925. // Open a transaction to the database
  70926. var transaction = this.db.transaction(["versions"], "readwrite");
  70927. // the transaction could abort because of a QuotaExceededError error
  70928. transaction.onabort = function (event) {
  70929. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70930. var error = event.srcElement['error'];
  70931. if (error && error.name === "QuotaExceededError") {
  70932. _this.hasReachedQuota = true;
  70933. }
  70934. }
  70935. catch (ex) { }
  70936. callback(-1);
  70937. };
  70938. transaction.oncomplete = function (event) {
  70939. callback(_this.manifestVersionFound);
  70940. };
  70941. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  70942. // Put the scene into the database
  70943. var addRequest = transaction.objectStore("versions").put(newVersion);
  70944. addRequest.onsuccess = function (event) {
  70945. };
  70946. addRequest.onerror = function (event) {
  70947. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  70948. };
  70949. }
  70950. catch (ex) {
  70951. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  70952. callback(-1);
  70953. }
  70954. }
  70955. else {
  70956. callback(-1);
  70957. }
  70958. };
  70959. /**
  70960. * Loads a file from database
  70961. * @param url defines the URL to load from
  70962. * @param sceneLoaded defines a callback to call on success
  70963. * @param progressCallBack defines a callback to call when progress changed
  70964. * @param errorCallback defines a callback to call on error
  70965. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70966. */
  70967. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70968. var _this = this;
  70969. var completeUrl = Database._ReturnFullUrlLocation(url);
  70970. var saveAndLoadFile = function () {
  70971. // the scene is not yet in the DB, let's try to save it
  70972. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70973. };
  70974. this._checkVersionFromDB(completeUrl, function (version) {
  70975. if (version !== -1) {
  70976. if (!_this.mustUpdateRessources) {
  70977. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70978. }
  70979. else {
  70980. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  70981. }
  70982. }
  70983. else {
  70984. if (errorCallback) {
  70985. errorCallback();
  70986. }
  70987. }
  70988. });
  70989. };
  70990. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70991. if (this.isSupported && this.db) {
  70992. var targetStore;
  70993. if (url.indexOf(".babylon") !== -1) {
  70994. targetStore = "scenes";
  70995. }
  70996. else {
  70997. targetStore = "textures";
  70998. }
  70999. var file;
  71000. var transaction = this.db.transaction([targetStore]);
  71001. transaction.oncomplete = function (event) {
  71002. if (file) {
  71003. callback(file.data);
  71004. }
  71005. // file was not found in DB
  71006. else {
  71007. notInDBCallback();
  71008. }
  71009. };
  71010. transaction.onabort = function (event) {
  71011. notInDBCallback();
  71012. };
  71013. var getRequest = transaction.objectStore(targetStore).get(url);
  71014. getRequest.onsuccess = function (event) {
  71015. file = (event.target).result;
  71016. };
  71017. getRequest.onerror = function (event) {
  71018. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  71019. notInDBCallback();
  71020. };
  71021. }
  71022. else {
  71023. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71024. callback();
  71025. }
  71026. };
  71027. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  71028. var _this = this;
  71029. if (this.isSupported) {
  71030. var targetStore;
  71031. if (url.indexOf(".babylon") !== -1) {
  71032. targetStore = "scenes";
  71033. }
  71034. else {
  71035. targetStore = "textures";
  71036. }
  71037. // Create XHR
  71038. var xhr = new XMLHttpRequest();
  71039. var fileData;
  71040. xhr.open("GET", url + "?" + Date.now(), true);
  71041. if (useArrayBuffer) {
  71042. xhr.responseType = "arraybuffer";
  71043. }
  71044. if (progressCallback) {
  71045. xhr.onprogress = progressCallback;
  71046. }
  71047. xhr.addEventListener("load", function () {
  71048. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  71049. // Blob as response (XHR2)
  71050. //fileData = xhr.responseText;
  71051. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  71052. if (!_this.hasReachedQuota && _this.db) {
  71053. // Open a transaction to the database
  71054. var transaction = _this.db.transaction([targetStore], "readwrite");
  71055. // the transaction could abort because of a QuotaExceededError error
  71056. transaction.onabort = function (event) {
  71057. try {
  71058. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  71059. var error = event.srcElement['error'];
  71060. if (error && error.name === "QuotaExceededError") {
  71061. _this.hasReachedQuota = true;
  71062. }
  71063. }
  71064. catch (ex) { }
  71065. callback(fileData);
  71066. };
  71067. transaction.oncomplete = function (event) {
  71068. callback(fileData);
  71069. };
  71070. var newFile;
  71071. if (targetStore === "scenes") {
  71072. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  71073. }
  71074. else {
  71075. newFile = { textureUrl: url, data: fileData };
  71076. }
  71077. try {
  71078. // Put the scene into the database
  71079. var addRequest = transaction.objectStore(targetStore).put(newFile);
  71080. addRequest.onsuccess = function (event) {
  71081. };
  71082. addRequest.onerror = function (event) {
  71083. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  71084. };
  71085. }
  71086. catch (ex) {
  71087. callback(fileData);
  71088. }
  71089. }
  71090. else {
  71091. callback(fileData);
  71092. }
  71093. }
  71094. else {
  71095. if (xhr.status >= 400 && errorCallback) {
  71096. errorCallback(xhr);
  71097. }
  71098. else {
  71099. callback();
  71100. }
  71101. }
  71102. }, false);
  71103. xhr.addEventListener("error", function (event) {
  71104. BABYLON.Tools.Error("error on XHR request.");
  71105. callback();
  71106. }, false);
  71107. xhr.send();
  71108. }
  71109. else {
  71110. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  71111. callback();
  71112. }
  71113. };
  71114. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  71115. Database.IsUASupportingBlobStorage = true;
  71116. /** Gets a boolean indicating if Database storate is enabled */
  71117. Database.IDBStorageEnabled = true;
  71118. Database._ParseURL = function (url) {
  71119. var a = document.createElement('a');
  71120. a.href = url;
  71121. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  71122. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  71123. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  71124. return absLocation;
  71125. };
  71126. Database._ReturnFullUrlLocation = function (url) {
  71127. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  71128. return (Database._ParseURL(window.location.href) + url);
  71129. }
  71130. else {
  71131. return url;
  71132. }
  71133. };
  71134. return Database;
  71135. }());
  71136. BABYLON.Database = Database;
  71137. })(BABYLON || (BABYLON = {}));
  71138. //# sourceMappingURL=babylon.database.js.map
  71139. var BABYLON;
  71140. (function (BABYLON) {
  71141. var FresnelParameters = /** @class */ (function () {
  71142. function FresnelParameters() {
  71143. this._isEnabled = true;
  71144. this.leftColor = BABYLON.Color3.White();
  71145. this.rightColor = BABYLON.Color3.Black();
  71146. this.bias = 0;
  71147. this.power = 1;
  71148. }
  71149. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  71150. get: function () {
  71151. return this._isEnabled;
  71152. },
  71153. set: function (value) {
  71154. if (this._isEnabled === value) {
  71155. return;
  71156. }
  71157. this._isEnabled = value;
  71158. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  71159. },
  71160. enumerable: true,
  71161. configurable: true
  71162. });
  71163. FresnelParameters.prototype.clone = function () {
  71164. var newFresnelParameters = new FresnelParameters();
  71165. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  71166. return newFresnelParameters;
  71167. };
  71168. FresnelParameters.prototype.serialize = function () {
  71169. var serializationObject = {};
  71170. serializationObject.isEnabled = this.isEnabled;
  71171. serializationObject.leftColor = this.leftColor.asArray();
  71172. serializationObject.rightColor = this.rightColor.asArray();
  71173. serializationObject.bias = this.bias;
  71174. serializationObject.power = this.power;
  71175. return serializationObject;
  71176. };
  71177. FresnelParameters.Parse = function (parsedFresnelParameters) {
  71178. var fresnelParameters = new FresnelParameters();
  71179. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  71180. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  71181. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  71182. fresnelParameters.bias = parsedFresnelParameters.bias;
  71183. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  71184. return fresnelParameters;
  71185. };
  71186. return FresnelParameters;
  71187. }());
  71188. BABYLON.FresnelParameters = FresnelParameters;
  71189. })(BABYLON || (BABYLON = {}));
  71190. //# sourceMappingURL=babylon.fresnelParameters.js.map
  71191. var BABYLON;
  71192. (function (BABYLON) {
  71193. var MultiMaterial = /** @class */ (function (_super) {
  71194. __extends(MultiMaterial, _super);
  71195. function MultiMaterial(name, scene) {
  71196. var _this = _super.call(this, name, scene, true) || this;
  71197. scene.multiMaterials.push(_this);
  71198. _this.subMaterials = new Array();
  71199. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  71200. return _this;
  71201. }
  71202. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  71203. get: function () {
  71204. return this._subMaterials;
  71205. },
  71206. set: function (value) {
  71207. this._subMaterials = value;
  71208. this._hookArray(value);
  71209. },
  71210. enumerable: true,
  71211. configurable: true
  71212. });
  71213. MultiMaterial.prototype._hookArray = function (array) {
  71214. var _this = this;
  71215. var oldPush = array.push;
  71216. array.push = function () {
  71217. var items = [];
  71218. for (var _i = 0; _i < arguments.length; _i++) {
  71219. items[_i] = arguments[_i];
  71220. }
  71221. var result = oldPush.apply(array, items);
  71222. _this._markAllSubMeshesAsTexturesDirty();
  71223. return result;
  71224. };
  71225. var oldSplice = array.splice;
  71226. array.splice = function (index, deleteCount) {
  71227. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71228. _this._markAllSubMeshesAsTexturesDirty();
  71229. return deleted;
  71230. };
  71231. };
  71232. // Properties
  71233. MultiMaterial.prototype.getSubMaterial = function (index) {
  71234. if (index < 0 || index >= this.subMaterials.length) {
  71235. return this.getScene().defaultMaterial;
  71236. }
  71237. return this.subMaterials[index];
  71238. };
  71239. MultiMaterial.prototype.getActiveTextures = function () {
  71240. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  71241. if (subMaterial) {
  71242. return subMaterial.getActiveTextures();
  71243. }
  71244. else {
  71245. return [];
  71246. }
  71247. }));
  71248. var _a;
  71249. };
  71250. // Methods
  71251. MultiMaterial.prototype.getClassName = function () {
  71252. return "MultiMaterial";
  71253. };
  71254. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  71255. for (var index = 0; index < this.subMaterials.length; index++) {
  71256. var subMaterial = this.subMaterials[index];
  71257. if (subMaterial) {
  71258. if (subMaterial.storeEffectOnSubMeshes) {
  71259. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  71260. return false;
  71261. }
  71262. continue;
  71263. }
  71264. if (!subMaterial.isReady(mesh)) {
  71265. return false;
  71266. }
  71267. }
  71268. }
  71269. return true;
  71270. };
  71271. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  71272. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  71273. for (var index = 0; index < this.subMaterials.length; index++) {
  71274. var subMaterial = null;
  71275. var current = this.subMaterials[index];
  71276. if (cloneChildren && current) {
  71277. subMaterial = current.clone(name + "-" + current.name);
  71278. }
  71279. else {
  71280. subMaterial = this.subMaterials[index];
  71281. }
  71282. newMultiMaterial.subMaterials.push(subMaterial);
  71283. }
  71284. return newMultiMaterial;
  71285. };
  71286. MultiMaterial.prototype.serialize = function () {
  71287. var serializationObject = {};
  71288. serializationObject.name = this.name;
  71289. serializationObject.id = this.id;
  71290. if (BABYLON.Tags) {
  71291. serializationObject.tags = BABYLON.Tags.GetTags(this);
  71292. }
  71293. serializationObject.materials = [];
  71294. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  71295. var subMat = this.subMaterials[matIndex];
  71296. if (subMat) {
  71297. serializationObject.materials.push(subMat.id);
  71298. }
  71299. else {
  71300. serializationObject.materials.push(null);
  71301. }
  71302. }
  71303. return serializationObject;
  71304. };
  71305. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  71306. var scene = this.getScene();
  71307. if (!scene) {
  71308. return;
  71309. }
  71310. var index = scene.multiMaterials.indexOf(this);
  71311. if (index >= 0) {
  71312. scene.multiMaterials.splice(index, 1);
  71313. }
  71314. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  71315. };
  71316. return MultiMaterial;
  71317. }(BABYLON.Material));
  71318. BABYLON.MultiMaterial = MultiMaterial;
  71319. })(BABYLON || (BABYLON = {}));
  71320. //# sourceMappingURL=babylon.multiMaterial.js.map
  71321. var BABYLON;
  71322. (function (BABYLON) {
  71323. var FreeCameraTouchInput = /** @class */ (function () {
  71324. function FreeCameraTouchInput() {
  71325. this._offsetX = null;
  71326. this._offsetY = null;
  71327. this._pointerPressed = new Array();
  71328. this.touchAngularSensibility = 200000.0;
  71329. this.touchMoveSensibility = 250.0;
  71330. }
  71331. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  71332. var _this = this;
  71333. var previousPosition = null;
  71334. if (this._pointerInput === undefined) {
  71335. this._onLostFocus = function (evt) {
  71336. _this._offsetX = null;
  71337. _this._offsetY = null;
  71338. };
  71339. this._pointerInput = function (p, s) {
  71340. var evt = p.event;
  71341. if (evt.pointerType === "mouse") {
  71342. return;
  71343. }
  71344. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  71345. if (!noPreventDefault) {
  71346. evt.preventDefault();
  71347. }
  71348. _this._pointerPressed.push(evt.pointerId);
  71349. if (_this._pointerPressed.length !== 1) {
  71350. return;
  71351. }
  71352. previousPosition = {
  71353. x: evt.clientX,
  71354. y: evt.clientY
  71355. };
  71356. }
  71357. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  71358. if (!noPreventDefault) {
  71359. evt.preventDefault();
  71360. }
  71361. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71362. if (index === -1) {
  71363. return;
  71364. }
  71365. _this._pointerPressed.splice(index, 1);
  71366. if (index != 0) {
  71367. return;
  71368. }
  71369. previousPosition = null;
  71370. _this._offsetX = null;
  71371. _this._offsetY = null;
  71372. }
  71373. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  71374. if (!noPreventDefault) {
  71375. evt.preventDefault();
  71376. }
  71377. if (!previousPosition) {
  71378. return;
  71379. }
  71380. var index = _this._pointerPressed.indexOf(evt.pointerId);
  71381. if (index != 0) {
  71382. return;
  71383. }
  71384. _this._offsetX = evt.clientX - previousPosition.x;
  71385. _this._offsetY = -(evt.clientY - previousPosition.y);
  71386. }
  71387. };
  71388. }
  71389. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  71390. if (this._onLostFocus) {
  71391. element.addEventListener("blur", this._onLostFocus);
  71392. }
  71393. };
  71394. FreeCameraTouchInput.prototype.detachControl = function (element) {
  71395. if (this._pointerInput && element) {
  71396. if (this._observer) {
  71397. this.camera.getScene().onPointerObservable.remove(this._observer);
  71398. this._observer = null;
  71399. }
  71400. if (this._onLostFocus) {
  71401. element.removeEventListener("blur", this._onLostFocus);
  71402. this._onLostFocus = null;
  71403. }
  71404. this._pointerPressed = [];
  71405. this._offsetX = null;
  71406. this._offsetY = null;
  71407. }
  71408. };
  71409. FreeCameraTouchInput.prototype.checkInputs = function () {
  71410. if (this._offsetX && this._offsetY) {
  71411. var camera = this.camera;
  71412. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  71413. if (this._pointerPressed.length > 1) {
  71414. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  71415. }
  71416. else {
  71417. var speed = camera._computeLocalCameraSpeed();
  71418. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  71419. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  71420. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  71421. }
  71422. }
  71423. };
  71424. FreeCameraTouchInput.prototype.getClassName = function () {
  71425. return "FreeCameraTouchInput";
  71426. };
  71427. FreeCameraTouchInput.prototype.getSimpleName = function () {
  71428. return "touch";
  71429. };
  71430. __decorate([
  71431. BABYLON.serialize()
  71432. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  71433. __decorate([
  71434. BABYLON.serialize()
  71435. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  71436. return FreeCameraTouchInput;
  71437. }());
  71438. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  71439. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  71440. })(BABYLON || (BABYLON = {}));
  71441. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  71442. var BABYLON;
  71443. (function (BABYLON) {
  71444. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  71445. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  71446. });
  71447. // We're mainly based on the logic defined into the FreeCamera code
  71448. var TouchCamera = /** @class */ (function (_super) {
  71449. __extends(TouchCamera, _super);
  71450. //-- end properties for backward compatibility for inputs
  71451. function TouchCamera(name, position, scene) {
  71452. var _this = _super.call(this, name, position, scene) || this;
  71453. _this.inputs.addTouch();
  71454. _this._setupInputs();
  71455. return _this;
  71456. }
  71457. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  71458. //-- Begin properties for backward compatibility for inputs
  71459. get: function () {
  71460. var touch = this.inputs.attached["touch"];
  71461. if (touch)
  71462. return touch.touchAngularSensibility;
  71463. return 0;
  71464. },
  71465. set: function (value) {
  71466. var touch = this.inputs.attached["touch"];
  71467. if (touch)
  71468. touch.touchAngularSensibility = value;
  71469. },
  71470. enumerable: true,
  71471. configurable: true
  71472. });
  71473. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  71474. get: function () {
  71475. var touch = this.inputs.attached["touch"];
  71476. if (touch)
  71477. return touch.touchMoveSensibility;
  71478. return 0;
  71479. },
  71480. set: function (value) {
  71481. var touch = this.inputs.attached["touch"];
  71482. if (touch)
  71483. touch.touchMoveSensibility = value;
  71484. },
  71485. enumerable: true,
  71486. configurable: true
  71487. });
  71488. TouchCamera.prototype.getClassName = function () {
  71489. return "TouchCamera";
  71490. };
  71491. TouchCamera.prototype._setupInputs = function () {
  71492. var mouse = this.inputs.attached["mouse"];
  71493. if (mouse) {
  71494. mouse.touchEnabled = false;
  71495. }
  71496. };
  71497. return TouchCamera;
  71498. }(BABYLON.FreeCamera));
  71499. BABYLON.TouchCamera = TouchCamera;
  71500. })(BABYLON || (BABYLON = {}));
  71501. //# sourceMappingURL=babylon.touchCamera.js.map
  71502. var BABYLON;
  71503. (function (BABYLON) {
  71504. var ProceduralTexture = /** @class */ (function (_super) {
  71505. __extends(ProceduralTexture, _super);
  71506. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  71507. if (fallbackTexture === void 0) { fallbackTexture = null; }
  71508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  71509. if (isCube === void 0) { isCube = false; }
  71510. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71511. _this.isCube = isCube;
  71512. _this.isEnabled = true;
  71513. _this._currentRefreshId = -1;
  71514. _this._refreshRate = 1;
  71515. _this._vertexBuffers = {};
  71516. _this._uniforms = new Array();
  71517. _this._samplers = new Array();
  71518. _this._textures = {};
  71519. _this._floats = {};
  71520. _this._ints = {};
  71521. _this._floatsArrays = {};
  71522. _this._colors3 = {};
  71523. _this._colors4 = {};
  71524. _this._vectors2 = {};
  71525. _this._vectors3 = {};
  71526. _this._matrices = {};
  71527. _this._fallbackTextureUsed = false;
  71528. scene = _this.getScene();
  71529. scene.proceduralTextures.push(_this);
  71530. _this._engine = scene.getEngine();
  71531. _this.name = name;
  71532. _this.isRenderTarget = true;
  71533. _this._size = size;
  71534. _this._generateMipMaps = generateMipMaps;
  71535. _this.setFragment(fragment);
  71536. _this._fallbackTexture = fallbackTexture;
  71537. if (isCube) {
  71538. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  71539. _this.setFloat("face", 0);
  71540. }
  71541. else {
  71542. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  71543. }
  71544. // VBO
  71545. var vertices = [];
  71546. vertices.push(1, 1);
  71547. vertices.push(-1, 1);
  71548. vertices.push(-1, -1);
  71549. vertices.push(1, -1);
  71550. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  71551. _this._createIndexBuffer();
  71552. return _this;
  71553. }
  71554. ProceduralTexture.prototype._createIndexBuffer = function () {
  71555. var engine = this._engine;
  71556. // Indices
  71557. var indices = [];
  71558. indices.push(0);
  71559. indices.push(1);
  71560. indices.push(2);
  71561. indices.push(0);
  71562. indices.push(2);
  71563. indices.push(3);
  71564. this._indexBuffer = engine.createIndexBuffer(indices);
  71565. };
  71566. ProceduralTexture.prototype._rebuild = function () {
  71567. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71568. if (vb) {
  71569. vb._rebuild();
  71570. }
  71571. this._createIndexBuffer();
  71572. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  71573. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  71574. }
  71575. };
  71576. ProceduralTexture.prototype.reset = function () {
  71577. if (this._effect === undefined) {
  71578. return;
  71579. }
  71580. var engine = this._engine;
  71581. engine._releaseEffect(this._effect);
  71582. };
  71583. ProceduralTexture.prototype.isReady = function () {
  71584. var _this = this;
  71585. var engine = this._engine;
  71586. var shaders;
  71587. if (!this._fragment) {
  71588. return false;
  71589. }
  71590. if (this._fallbackTextureUsed) {
  71591. return true;
  71592. }
  71593. if (this._fragment.fragmentElement !== undefined) {
  71594. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  71595. }
  71596. else {
  71597. shaders = { vertex: "procedural", fragment: this._fragment };
  71598. }
  71599. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  71600. _this.releaseInternalTexture();
  71601. if (_this._fallbackTexture) {
  71602. _this._texture = _this._fallbackTexture._texture;
  71603. if (_this._texture) {
  71604. _this._texture.incrementReferences();
  71605. }
  71606. }
  71607. _this._fallbackTextureUsed = true;
  71608. });
  71609. return this._effect.isReady();
  71610. };
  71611. ProceduralTexture.prototype.resetRefreshCounter = function () {
  71612. this._currentRefreshId = -1;
  71613. };
  71614. ProceduralTexture.prototype.setFragment = function (fragment) {
  71615. this._fragment = fragment;
  71616. };
  71617. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  71618. get: function () {
  71619. return this._refreshRate;
  71620. },
  71621. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71622. set: function (value) {
  71623. this._refreshRate = value;
  71624. this.resetRefreshCounter();
  71625. },
  71626. enumerable: true,
  71627. configurable: true
  71628. });
  71629. ProceduralTexture.prototype._shouldRender = function () {
  71630. if (!this.isEnabled || !this.isReady() || !this._texture) {
  71631. return false;
  71632. }
  71633. if (this._fallbackTextureUsed) {
  71634. return false;
  71635. }
  71636. if (this._currentRefreshId === -1) { // At least render once
  71637. this._currentRefreshId = 1;
  71638. return true;
  71639. }
  71640. if (this.refreshRate === this._currentRefreshId) {
  71641. this._currentRefreshId = 1;
  71642. return true;
  71643. }
  71644. this._currentRefreshId++;
  71645. return false;
  71646. };
  71647. ProceduralTexture.prototype.getRenderSize = function () {
  71648. return this._size;
  71649. };
  71650. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  71651. if (this._fallbackTextureUsed) {
  71652. return;
  71653. }
  71654. this.releaseInternalTexture();
  71655. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  71656. // Update properties
  71657. this._size = size;
  71658. this._generateMipMaps = generateMipMaps;
  71659. };
  71660. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  71661. if (this._uniforms.indexOf(uniformName) === -1) {
  71662. this._uniforms.push(uniformName);
  71663. }
  71664. };
  71665. ProceduralTexture.prototype.setTexture = function (name, texture) {
  71666. if (this._samplers.indexOf(name) === -1) {
  71667. this._samplers.push(name);
  71668. }
  71669. this._textures[name] = texture;
  71670. return this;
  71671. };
  71672. ProceduralTexture.prototype.setFloat = function (name, value) {
  71673. this._checkUniform(name);
  71674. this._floats[name] = value;
  71675. return this;
  71676. };
  71677. /**
  71678. * Set the value of an uniform to an integer value
  71679. * @param name defines the name of the uniform
  71680. * @param value defines the value to set
  71681. * @returns the current procedural texture
  71682. */
  71683. ProceduralTexture.prototype.setInt = function (name, value) {
  71684. this._checkUniform(name);
  71685. this._ints[name] = value;
  71686. return this;
  71687. };
  71688. ProceduralTexture.prototype.setFloats = function (name, value) {
  71689. this._checkUniform(name);
  71690. this._floatsArrays[name] = value;
  71691. return this;
  71692. };
  71693. ProceduralTexture.prototype.setColor3 = function (name, value) {
  71694. this._checkUniform(name);
  71695. this._colors3[name] = value;
  71696. return this;
  71697. };
  71698. ProceduralTexture.prototype.setColor4 = function (name, value) {
  71699. this._checkUniform(name);
  71700. this._colors4[name] = value;
  71701. return this;
  71702. };
  71703. ProceduralTexture.prototype.setVector2 = function (name, value) {
  71704. this._checkUniform(name);
  71705. this._vectors2[name] = value;
  71706. return this;
  71707. };
  71708. ProceduralTexture.prototype.setVector3 = function (name, value) {
  71709. this._checkUniform(name);
  71710. this._vectors3[name] = value;
  71711. return this;
  71712. };
  71713. ProceduralTexture.prototype.setMatrix = function (name, value) {
  71714. this._checkUniform(name);
  71715. this._matrices[name] = value;
  71716. return this;
  71717. };
  71718. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71719. var scene = this.getScene();
  71720. if (!scene) {
  71721. return;
  71722. }
  71723. var engine = this._engine;
  71724. // Render
  71725. engine.enableEffect(this._effect);
  71726. engine.setState(false);
  71727. // Texture
  71728. for (var name in this._textures) {
  71729. this._effect.setTexture(name, this._textures[name]);
  71730. }
  71731. // Float
  71732. for (name in this._ints) {
  71733. this._effect.setInt(name, this._ints[name]);
  71734. }
  71735. // Float
  71736. for (name in this._floats) {
  71737. this._effect.setFloat(name, this._floats[name]);
  71738. }
  71739. // Floats
  71740. for (name in this._floatsArrays) {
  71741. this._effect.setArray(name, this._floatsArrays[name]);
  71742. }
  71743. // Color3
  71744. for (name in this._colors3) {
  71745. this._effect.setColor3(name, this._colors3[name]);
  71746. }
  71747. // Color4
  71748. for (name in this._colors4) {
  71749. var color = this._colors4[name];
  71750. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  71751. }
  71752. // Vector2
  71753. for (name in this._vectors2) {
  71754. this._effect.setVector2(name, this._vectors2[name]);
  71755. }
  71756. // Vector3
  71757. for (name in this._vectors3) {
  71758. this._effect.setVector3(name, this._vectors3[name]);
  71759. }
  71760. // Matrix
  71761. for (name in this._matrices) {
  71762. this._effect.setMatrix(name, this._matrices[name]);
  71763. }
  71764. if (!this._texture) {
  71765. return;
  71766. }
  71767. if (this.isCube) {
  71768. for (var face = 0; face < 6; face++) {
  71769. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  71770. // VBOs
  71771. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71772. this._effect.setFloat("face", face);
  71773. // Clear
  71774. engine.clear(scene.clearColor, true, true, true);
  71775. // Draw order
  71776. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71777. // Mipmaps
  71778. if (face === 5) {
  71779. engine.generateMipMapsForCubemap(this._texture);
  71780. }
  71781. }
  71782. }
  71783. else {
  71784. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  71785. // VBOs
  71786. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  71787. // Clear
  71788. engine.clear(scene.clearColor, true, true, true);
  71789. // Draw order
  71790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  71791. }
  71792. // Unbind
  71793. engine.unBindFramebuffer(this._texture, this.isCube);
  71794. if (this.onGenerated) {
  71795. this.onGenerated();
  71796. }
  71797. };
  71798. ProceduralTexture.prototype.clone = function () {
  71799. var textureSize = this.getSize();
  71800. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  71801. // Base texture
  71802. newTexture.hasAlpha = this.hasAlpha;
  71803. newTexture.level = this.level;
  71804. // RenderTarget Texture
  71805. newTexture.coordinatesMode = this.coordinatesMode;
  71806. return newTexture;
  71807. };
  71808. ProceduralTexture.prototype.dispose = function () {
  71809. var scene = this.getScene();
  71810. if (!scene) {
  71811. return;
  71812. }
  71813. var index = scene.proceduralTextures.indexOf(this);
  71814. if (index >= 0) {
  71815. scene.proceduralTextures.splice(index, 1);
  71816. }
  71817. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71818. if (vertexBuffer) {
  71819. vertexBuffer.dispose();
  71820. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71821. }
  71822. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  71823. this._indexBuffer = null;
  71824. }
  71825. _super.prototype.dispose.call(this);
  71826. };
  71827. __decorate([
  71828. BABYLON.serialize()
  71829. ], ProceduralTexture.prototype, "_size", void 0);
  71830. __decorate([
  71831. BABYLON.serialize()
  71832. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  71833. __decorate([
  71834. BABYLON.serialize()
  71835. ], ProceduralTexture.prototype, "isEnabled", void 0);
  71836. __decorate([
  71837. BABYLON.serialize()
  71838. ], ProceduralTexture.prototype, "refreshRate", null);
  71839. return ProceduralTexture;
  71840. }(BABYLON.Texture));
  71841. BABYLON.ProceduralTexture = ProceduralTexture;
  71842. })(BABYLON || (BABYLON = {}));
  71843. //# sourceMappingURL=babylon.proceduralTexture.js.map
  71844. var BABYLON;
  71845. (function (BABYLON) {
  71846. var CustomProceduralTexture = /** @class */ (function (_super) {
  71847. __extends(CustomProceduralTexture, _super);
  71848. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  71849. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  71850. _this._animate = true;
  71851. _this._time = 0;
  71852. _this._texturePath = texturePath;
  71853. //Try to load json
  71854. _this.loadJson(texturePath);
  71855. _this.refreshRate = 1;
  71856. return _this;
  71857. }
  71858. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  71859. var _this = this;
  71860. var noConfigFile = function () {
  71861. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  71862. try {
  71863. _this.setFragment(_this._texturePath);
  71864. }
  71865. catch (ex) {
  71866. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  71867. }
  71868. };
  71869. var configFileUrl = jsonUrl + "/config.json";
  71870. var xhr = new XMLHttpRequest();
  71871. xhr.open("GET", configFileUrl, true);
  71872. xhr.addEventListener("load", function () {
  71873. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71874. try {
  71875. _this._config = JSON.parse(xhr.response);
  71876. _this.updateShaderUniforms();
  71877. _this.updateTextures();
  71878. _this.setFragment(_this._texturePath + "/custom");
  71879. _this._animate = _this._config.animate;
  71880. _this.refreshRate = _this._config.refreshrate;
  71881. }
  71882. catch (ex) {
  71883. noConfigFile();
  71884. }
  71885. }
  71886. else {
  71887. noConfigFile();
  71888. }
  71889. }, false);
  71890. xhr.addEventListener("error", function () {
  71891. noConfigFile();
  71892. }, false);
  71893. try {
  71894. xhr.send();
  71895. }
  71896. catch (ex) {
  71897. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  71898. }
  71899. };
  71900. CustomProceduralTexture.prototype.isReady = function () {
  71901. if (!_super.prototype.isReady.call(this)) {
  71902. return false;
  71903. }
  71904. for (var name in this._textures) {
  71905. var texture = this._textures[name];
  71906. if (!texture.isReady()) {
  71907. return false;
  71908. }
  71909. }
  71910. return true;
  71911. };
  71912. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  71913. var scene = this.getScene();
  71914. if (this._animate && scene) {
  71915. this._time += scene.getAnimationRatio() * 0.03;
  71916. this.updateShaderUniforms();
  71917. }
  71918. _super.prototype.render.call(this, useCameraPostProcess);
  71919. };
  71920. CustomProceduralTexture.prototype.updateTextures = function () {
  71921. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  71922. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  71923. }
  71924. };
  71925. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  71926. if (this._config) {
  71927. for (var j = 0; j < this._config.uniforms.length; j++) {
  71928. var uniform = this._config.uniforms[j];
  71929. switch (uniform.type) {
  71930. case "float":
  71931. this.setFloat(uniform.name, uniform.value);
  71932. break;
  71933. case "color3":
  71934. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  71935. break;
  71936. case "color4":
  71937. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  71938. break;
  71939. case "vector2":
  71940. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  71941. break;
  71942. case "vector3":
  71943. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  71944. break;
  71945. }
  71946. }
  71947. }
  71948. this.setFloat("time", this._time);
  71949. };
  71950. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  71951. get: function () {
  71952. return this._animate;
  71953. },
  71954. set: function (value) {
  71955. this._animate = value;
  71956. },
  71957. enumerable: true,
  71958. configurable: true
  71959. });
  71960. return CustomProceduralTexture;
  71961. }(BABYLON.ProceduralTexture));
  71962. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  71963. })(BABYLON || (BABYLON = {}));
  71964. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  71965. var BABYLON;
  71966. (function (BABYLON) {
  71967. var FreeCameraGamepadInput = /** @class */ (function () {
  71968. function FreeCameraGamepadInput() {
  71969. this.gamepadAngularSensibility = 200;
  71970. this.gamepadMoveSensibility = 40;
  71971. // private members
  71972. this._cameraTransform = BABYLON.Matrix.Identity();
  71973. this._deltaTransform = BABYLON.Vector3.Zero();
  71974. this._vector3 = BABYLON.Vector3.Zero();
  71975. this._vector2 = BABYLON.Vector2.Zero();
  71976. }
  71977. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71978. var _this = this;
  71979. var manager = this.camera.getScene().gamepadManager;
  71980. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71981. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71982. // prioritize XBOX gamepads.
  71983. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71984. _this.gamepad = gamepad;
  71985. }
  71986. }
  71987. });
  71988. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71989. if (_this.gamepad === gamepad) {
  71990. _this.gamepad = null;
  71991. }
  71992. });
  71993. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71994. };
  71995. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71996. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71997. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71998. this.gamepad = null;
  71999. };
  72000. FreeCameraGamepadInput.prototype.checkInputs = function () {
  72001. if (this.gamepad && this.gamepad.leftStick) {
  72002. var camera = this.camera;
  72003. var LSValues = this.gamepad.leftStick;
  72004. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  72005. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72006. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  72007. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  72008. var RSValues = this.gamepad.rightStick;
  72009. if (RSValues) {
  72010. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  72011. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  72012. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  72013. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  72014. }
  72015. else {
  72016. RSValues = { x: 0, y: 0 };
  72017. }
  72018. if (!camera.rotationQuaternion) {
  72019. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  72020. }
  72021. else {
  72022. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  72023. }
  72024. var speed = camera._computeLocalCameraSpeed() * 50.0;
  72025. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  72026. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  72027. camera.cameraDirection.addInPlace(this._deltaTransform);
  72028. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  72029. camera.cameraRotation.addInPlace(this._vector2);
  72030. }
  72031. };
  72032. FreeCameraGamepadInput.prototype.getClassName = function () {
  72033. return "FreeCameraGamepadInput";
  72034. };
  72035. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  72036. return "gamepad";
  72037. };
  72038. __decorate([
  72039. BABYLON.serialize()
  72040. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  72041. __decorate([
  72042. BABYLON.serialize()
  72043. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72044. return FreeCameraGamepadInput;
  72045. }());
  72046. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  72047. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  72048. })(BABYLON || (BABYLON = {}));
  72049. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  72050. var BABYLON;
  72051. (function (BABYLON) {
  72052. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  72053. function ArcRotateCameraGamepadInput() {
  72054. this.gamepadRotationSensibility = 80;
  72055. this.gamepadMoveSensibility = 40;
  72056. }
  72057. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  72058. var _this = this;
  72059. var manager = this.camera.getScene().gamepadManager;
  72060. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72061. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72062. // prioritize XBOX gamepads.
  72063. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  72064. _this.gamepad = gamepad;
  72065. }
  72066. }
  72067. });
  72068. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72069. if (_this.gamepad === gamepad) {
  72070. _this.gamepad = null;
  72071. }
  72072. });
  72073. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  72074. };
  72075. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  72076. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72077. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72078. this.gamepad = null;
  72079. };
  72080. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  72081. if (this.gamepad) {
  72082. var camera = this.camera;
  72083. var RSValues = this.gamepad.rightStick;
  72084. if (RSValues) {
  72085. if (RSValues.x != 0) {
  72086. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  72087. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  72088. camera.inertialAlphaOffset += normalizedRX;
  72089. }
  72090. }
  72091. if (RSValues.y != 0) {
  72092. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  72093. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  72094. camera.inertialBetaOffset += normalizedRY;
  72095. }
  72096. }
  72097. }
  72098. var LSValues = this.gamepad.leftStick;
  72099. if (LSValues && LSValues.y != 0) {
  72100. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  72101. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  72102. this.camera.inertialRadiusOffset -= normalizedLY;
  72103. }
  72104. }
  72105. }
  72106. };
  72107. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  72108. return "ArcRotateCameraGamepadInput";
  72109. };
  72110. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  72111. return "gamepad";
  72112. };
  72113. __decorate([
  72114. BABYLON.serialize()
  72115. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  72116. __decorate([
  72117. BABYLON.serialize()
  72118. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  72119. return ArcRotateCameraGamepadInput;
  72120. }());
  72121. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  72122. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  72123. })(BABYLON || (BABYLON = {}));
  72124. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  72125. var BABYLON;
  72126. (function (BABYLON) {
  72127. var GamepadManager = /** @class */ (function () {
  72128. function GamepadManager(_scene) {
  72129. var _this = this;
  72130. this._scene = _scene;
  72131. this._babylonGamepads = [];
  72132. this._oneGamepadConnected = false;
  72133. this._isMonitoring = false;
  72134. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  72135. if (!BABYLON.Tools.IsWindowObjectExist()) {
  72136. this._gamepadEventSupported = false;
  72137. }
  72138. else {
  72139. this._gamepadEventSupported = 'GamepadEvent' in window;
  72140. this._gamepadSupport = (navigator.getGamepads ||
  72141. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  72142. }
  72143. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  72144. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  72145. for (var i in _this._babylonGamepads) {
  72146. var gamepad = _this._babylonGamepads[i];
  72147. if (gamepad && gamepad._isConnected) {
  72148. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  72149. }
  72150. }
  72151. });
  72152. this._onGamepadConnectedEvent = function (evt) {
  72153. var gamepad = evt.gamepad;
  72154. if (gamepad.index in _this._babylonGamepads) {
  72155. if (_this._babylonGamepads[gamepad.index].isConnected) {
  72156. return;
  72157. }
  72158. }
  72159. var newGamepad;
  72160. if (_this._babylonGamepads[gamepad.index]) {
  72161. newGamepad = _this._babylonGamepads[gamepad.index];
  72162. newGamepad.browserGamepad = gamepad;
  72163. newGamepad._isConnected = true;
  72164. }
  72165. else {
  72166. newGamepad = _this._addNewGamepad(gamepad);
  72167. }
  72168. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72169. _this._startMonitoringGamepads();
  72170. };
  72171. this._onGamepadDisconnectedEvent = function (evt) {
  72172. var gamepad = evt.gamepad;
  72173. // Remove the gamepad from the list of gamepads to monitor.
  72174. for (var i in _this._babylonGamepads) {
  72175. if (_this._babylonGamepads[i].index === gamepad.index) {
  72176. var disconnectedGamepad = _this._babylonGamepads[i];
  72177. disconnectedGamepad._isConnected = false;
  72178. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  72179. break;
  72180. }
  72181. }
  72182. };
  72183. if (this._gamepadSupport) {
  72184. //first add already-connected gamepads
  72185. this._updateGamepadObjects();
  72186. if (this._babylonGamepads.length) {
  72187. this._startMonitoringGamepads();
  72188. }
  72189. // Checking if the gamepad connected event is supported (like in Firefox)
  72190. if (this._gamepadEventSupported) {
  72191. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  72192. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  72193. }
  72194. else {
  72195. this._startMonitoringGamepads();
  72196. }
  72197. }
  72198. }
  72199. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  72200. get: function () {
  72201. return this._babylonGamepads;
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. GamepadManager.prototype.getGamepadByType = function (type) {
  72207. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  72208. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  72209. var gamepad = _a[_i];
  72210. if (gamepad && gamepad.type === type) {
  72211. return gamepad;
  72212. }
  72213. }
  72214. return null;
  72215. };
  72216. GamepadManager.prototype.dispose = function () {
  72217. if (this._gamepadEventSupported) {
  72218. if (this._onGamepadConnectedEvent) {
  72219. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  72220. }
  72221. if (this._onGamepadDisconnectedEvent) {
  72222. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  72223. }
  72224. this._onGamepadConnectedEvent = null;
  72225. this._onGamepadDisconnectedEvent = null;
  72226. }
  72227. this._babylonGamepads.forEach(function (gamepad) {
  72228. gamepad.dispose();
  72229. });
  72230. this.onGamepadConnectedObservable.clear();
  72231. this.onGamepadDisconnectedObservable.clear();
  72232. this._oneGamepadConnected = false;
  72233. this._stopMonitoringGamepads();
  72234. this._babylonGamepads = [];
  72235. };
  72236. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  72237. if (!this._oneGamepadConnected) {
  72238. this._oneGamepadConnected = true;
  72239. }
  72240. var newGamepad;
  72241. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  72242. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  72243. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  72244. }
  72245. // if pose is supported, use the (WebVR) pose enabled controller
  72246. else if (gamepad.pose) {
  72247. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  72248. }
  72249. else {
  72250. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  72251. }
  72252. this._babylonGamepads[newGamepad.index] = newGamepad;
  72253. return newGamepad;
  72254. };
  72255. GamepadManager.prototype._startMonitoringGamepads = function () {
  72256. if (!this._isMonitoring) {
  72257. this._isMonitoring = true;
  72258. //back-comp
  72259. if (!this._scene) {
  72260. this._checkGamepadsStatus();
  72261. }
  72262. }
  72263. };
  72264. GamepadManager.prototype._stopMonitoringGamepads = function () {
  72265. this._isMonitoring = false;
  72266. };
  72267. GamepadManager.prototype._checkGamepadsStatus = function () {
  72268. var _this = this;
  72269. // Hack to be compatible Chrome
  72270. this._updateGamepadObjects();
  72271. for (var i in this._babylonGamepads) {
  72272. var gamepad = this._babylonGamepads[i];
  72273. if (!gamepad || !gamepad.isConnected) {
  72274. continue;
  72275. }
  72276. gamepad.update();
  72277. }
  72278. if (this._isMonitoring && !this._scene) {
  72279. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  72280. }
  72281. };
  72282. // This function is called only on Chrome, which does not properly support
  72283. // connection/disconnection events and forces you to recopy again the gamepad object
  72284. GamepadManager.prototype._updateGamepadObjects = function () {
  72285. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  72286. for (var i = 0; i < gamepads.length; i++) {
  72287. var gamepad = gamepads[i];
  72288. if (gamepad) {
  72289. if (!this._babylonGamepads[gamepad.index]) {
  72290. var newGamepad = this._addNewGamepad(gamepad);
  72291. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  72292. }
  72293. else {
  72294. // Forced to copy again this object for Chrome for unknown reason
  72295. this._babylonGamepads[i].browserGamepad = gamepad;
  72296. if (!this._babylonGamepads[i].isConnected) {
  72297. this._babylonGamepads[i]._isConnected = true;
  72298. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  72299. }
  72300. }
  72301. }
  72302. }
  72303. };
  72304. return GamepadManager;
  72305. }());
  72306. BABYLON.GamepadManager = GamepadManager;
  72307. })(BABYLON || (BABYLON = {}));
  72308. //# sourceMappingURL=babylon.gamepadManager.js.map
  72309. var BABYLON;
  72310. (function (BABYLON) {
  72311. var StickValues = /** @class */ (function () {
  72312. function StickValues(x, y) {
  72313. this.x = x;
  72314. this.y = y;
  72315. }
  72316. return StickValues;
  72317. }());
  72318. BABYLON.StickValues = StickValues;
  72319. var Gamepad = /** @class */ (function () {
  72320. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  72321. if (leftStickX === void 0) { leftStickX = 0; }
  72322. if (leftStickY === void 0) { leftStickY = 1; }
  72323. if (rightStickX === void 0) { rightStickX = 2; }
  72324. if (rightStickY === void 0) { rightStickY = 3; }
  72325. this.id = id;
  72326. this.index = index;
  72327. this.browserGamepad = browserGamepad;
  72328. this._isConnected = true;
  72329. this._invertLeftStickY = false;
  72330. this.type = Gamepad.GAMEPAD;
  72331. this._leftStickAxisX = leftStickX;
  72332. this._leftStickAxisY = leftStickY;
  72333. this._rightStickAxisX = rightStickX;
  72334. this._rightStickAxisY = rightStickY;
  72335. if (this.browserGamepad.axes.length >= 2) {
  72336. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72337. }
  72338. if (this.browserGamepad.axes.length >= 4) {
  72339. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72340. }
  72341. }
  72342. Object.defineProperty(Gamepad.prototype, "isConnected", {
  72343. get: function () {
  72344. return this._isConnected;
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Gamepad.prototype.onleftstickchanged = function (callback) {
  72350. this._onleftstickchanged = callback;
  72351. };
  72352. Gamepad.prototype.onrightstickchanged = function (callback) {
  72353. this._onrightstickchanged = callback;
  72354. };
  72355. Object.defineProperty(Gamepad.prototype, "leftStick", {
  72356. get: function () {
  72357. return this._leftStick;
  72358. },
  72359. set: function (newValues) {
  72360. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  72361. this._onleftstickchanged(newValues);
  72362. }
  72363. this._leftStick = newValues;
  72364. },
  72365. enumerable: true,
  72366. configurable: true
  72367. });
  72368. Object.defineProperty(Gamepad.prototype, "rightStick", {
  72369. get: function () {
  72370. return this._rightStick;
  72371. },
  72372. set: function (newValues) {
  72373. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  72374. this._onrightstickchanged(newValues);
  72375. }
  72376. this._rightStick = newValues;
  72377. },
  72378. enumerable: true,
  72379. configurable: true
  72380. });
  72381. Gamepad.prototype.update = function () {
  72382. if (this._leftStick) {
  72383. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  72384. if (this._invertLeftStickY) {
  72385. this.leftStick.y *= -1;
  72386. }
  72387. }
  72388. if (this._rightStick) {
  72389. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  72390. }
  72391. };
  72392. Gamepad.prototype.dispose = function () {
  72393. };
  72394. Gamepad.GAMEPAD = 0;
  72395. Gamepad.GENERIC = 1;
  72396. Gamepad.XBOX = 2;
  72397. Gamepad.POSE_ENABLED = 3;
  72398. return Gamepad;
  72399. }());
  72400. BABYLON.Gamepad = Gamepad;
  72401. var GenericPad = /** @class */ (function (_super) {
  72402. __extends(GenericPad, _super);
  72403. function GenericPad(id, index, browserGamepad) {
  72404. var _this = _super.call(this, id, index, browserGamepad) || this;
  72405. _this.onButtonDownObservable = new BABYLON.Observable();
  72406. _this.onButtonUpObservable = new BABYLON.Observable();
  72407. _this.type = Gamepad.GENERIC;
  72408. _this._buttons = new Array(browserGamepad.buttons.length);
  72409. return _this;
  72410. }
  72411. GenericPad.prototype.onbuttondown = function (callback) {
  72412. this._onbuttondown = callback;
  72413. };
  72414. GenericPad.prototype.onbuttonup = function (callback) {
  72415. this._onbuttonup = callback;
  72416. };
  72417. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  72418. if (newValue !== currentValue) {
  72419. if (newValue === 1) {
  72420. if (this._onbuttondown) {
  72421. this._onbuttondown(buttonIndex);
  72422. }
  72423. this.onButtonDownObservable.notifyObservers(buttonIndex);
  72424. }
  72425. if (newValue === 0) {
  72426. if (this._onbuttonup) {
  72427. this._onbuttonup(buttonIndex);
  72428. }
  72429. this.onButtonUpObservable.notifyObservers(buttonIndex);
  72430. }
  72431. }
  72432. return newValue;
  72433. };
  72434. GenericPad.prototype.update = function () {
  72435. _super.prototype.update.call(this);
  72436. for (var index = 0; index < this._buttons.length; index++) {
  72437. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  72438. }
  72439. };
  72440. GenericPad.prototype.dispose = function () {
  72441. _super.prototype.dispose.call(this);
  72442. this.onButtonDownObservable.clear();
  72443. this.onButtonUpObservable.clear();
  72444. };
  72445. return GenericPad;
  72446. }(Gamepad));
  72447. BABYLON.GenericPad = GenericPad;
  72448. })(BABYLON || (BABYLON = {}));
  72449. //# sourceMappingURL=babylon.gamepad.js.map
  72450. var BABYLON;
  72451. (function (BABYLON) {
  72452. /**
  72453. * Defines supported buttons for XBox360 compatible gamepads
  72454. */
  72455. var Xbox360Button;
  72456. (function (Xbox360Button) {
  72457. /** A */
  72458. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  72459. /** B */
  72460. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  72461. /** X */
  72462. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  72463. /** Y */
  72464. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  72465. /** Start */
  72466. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  72467. /** Back */
  72468. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  72469. /** Left button */
  72470. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  72471. /** Right button */
  72472. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  72473. /** Left stick */
  72474. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  72475. /** Right stick */
  72476. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  72477. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  72478. /** Defines values for XBox360 DPad */
  72479. var Xbox360Dpad;
  72480. (function (Xbox360Dpad) {
  72481. /** Up */
  72482. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  72483. /** Down */
  72484. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  72485. /** Left */
  72486. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  72487. /** Right */
  72488. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  72489. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  72490. /**
  72491. * Defines a XBox360 gamepad
  72492. */
  72493. var Xbox360Pad = /** @class */ (function (_super) {
  72494. __extends(Xbox360Pad, _super);
  72495. /**
  72496. * Creates a new XBox360 gamepad object
  72497. * @param id defines the id of this gamepad
  72498. * @param index defines its index
  72499. * @param gamepad defines the internal HTML gamepad object
  72500. * @param xboxOne defines if it is a XBox One gamepad
  72501. */
  72502. function Xbox360Pad(id, index, gamepad, xboxOne) {
  72503. if (xboxOne === void 0) { xboxOne = false; }
  72504. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  72505. _this._leftTrigger = 0;
  72506. _this._rightTrigger = 0;
  72507. /** Observable raised when a button is pressed */
  72508. _this.onButtonDownObservable = new BABYLON.Observable();
  72509. /** Observable raised when a button is released */
  72510. _this.onButtonUpObservable = new BABYLON.Observable();
  72511. /** Observable raised when a pad is pressed */
  72512. _this.onPadDownObservable = new BABYLON.Observable();
  72513. /** Observable raised when a pad is released */
  72514. _this.onPadUpObservable = new BABYLON.Observable();
  72515. _this._buttonA = 0;
  72516. _this._buttonB = 0;
  72517. _this._buttonX = 0;
  72518. _this._buttonY = 0;
  72519. _this._buttonBack = 0;
  72520. _this._buttonStart = 0;
  72521. _this._buttonLB = 0;
  72522. _this._buttonRB = 0;
  72523. _this._buttonLeftStick = 0;
  72524. _this._buttonRightStick = 0;
  72525. _this._dPadUp = 0;
  72526. _this._dPadDown = 0;
  72527. _this._dPadLeft = 0;
  72528. _this._dPadRight = 0;
  72529. _this._isXboxOnePad = false;
  72530. _this.type = BABYLON.Gamepad.XBOX;
  72531. _this._isXboxOnePad = xboxOne;
  72532. return _this;
  72533. }
  72534. /**
  72535. * Defines the callback to call when left trigger is pressed
  72536. * @param callback defines the callback to use
  72537. */
  72538. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  72539. this._onlefttriggerchanged = callback;
  72540. };
  72541. /**
  72542. * Defines the callback to call when right trigger is pressed
  72543. * @param callback defines the callback to use
  72544. */
  72545. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  72546. this._onrighttriggerchanged = callback;
  72547. };
  72548. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  72549. /**
  72550. * Gets or sets left trigger value
  72551. */
  72552. get: function () {
  72553. return this._leftTrigger;
  72554. },
  72555. set: function (newValue) {
  72556. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  72557. this._onlefttriggerchanged(newValue);
  72558. }
  72559. this._leftTrigger = newValue;
  72560. },
  72561. enumerable: true,
  72562. configurable: true
  72563. });
  72564. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  72565. /**
  72566. * Gets or sets right trigger value
  72567. */
  72568. get: function () {
  72569. return this._rightTrigger;
  72570. },
  72571. set: function (newValue) {
  72572. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  72573. this._onrighttriggerchanged(newValue);
  72574. }
  72575. this._rightTrigger = newValue;
  72576. },
  72577. enumerable: true,
  72578. configurable: true
  72579. });
  72580. /**
  72581. * Defines the callback to call when a button is pressed
  72582. * @param callback defines the callback to use
  72583. */
  72584. Xbox360Pad.prototype.onbuttondown = function (callback) {
  72585. this._onbuttondown = callback;
  72586. };
  72587. /**
  72588. * Defines the callback to call when a button is released
  72589. * @param callback defines the callback to use
  72590. */
  72591. Xbox360Pad.prototype.onbuttonup = function (callback) {
  72592. this._onbuttonup = callback;
  72593. };
  72594. /**
  72595. * Defines the callback to call when a pad is pressed
  72596. * @param callback defines the callback to use
  72597. */
  72598. Xbox360Pad.prototype.ondpaddown = function (callback) {
  72599. this._ondpaddown = callback;
  72600. };
  72601. /**
  72602. * Defines the callback to call when a pad is released
  72603. * @param callback defines the callback to use
  72604. */
  72605. Xbox360Pad.prototype.ondpadup = function (callback) {
  72606. this._ondpadup = callback;
  72607. };
  72608. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  72609. if (newValue !== currentValue) {
  72610. if (newValue === 1) {
  72611. if (this._onbuttondown) {
  72612. this._onbuttondown(buttonType);
  72613. }
  72614. this.onButtonDownObservable.notifyObservers(buttonType);
  72615. }
  72616. if (newValue === 0) {
  72617. if (this._onbuttonup) {
  72618. this._onbuttonup(buttonType);
  72619. }
  72620. this.onButtonUpObservable.notifyObservers(buttonType);
  72621. }
  72622. }
  72623. return newValue;
  72624. };
  72625. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  72626. if (newValue !== currentValue) {
  72627. if (newValue === 1) {
  72628. if (this._ondpaddown) {
  72629. this._ondpaddown(buttonType);
  72630. }
  72631. this.onPadDownObservable.notifyObservers(buttonType);
  72632. }
  72633. if (newValue === 0) {
  72634. if (this._ondpadup) {
  72635. this._ondpadup(buttonType);
  72636. }
  72637. this.onPadUpObservable.notifyObservers(buttonType);
  72638. }
  72639. }
  72640. return newValue;
  72641. };
  72642. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  72643. /** Gets or sets value of A button */
  72644. get: function () {
  72645. return this._buttonA;
  72646. },
  72647. set: function (value) {
  72648. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  72649. },
  72650. enumerable: true,
  72651. configurable: true
  72652. });
  72653. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  72654. /** Gets or sets value of B button */
  72655. get: function () {
  72656. return this._buttonB;
  72657. },
  72658. set: function (value) {
  72659. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  72660. },
  72661. enumerable: true,
  72662. configurable: true
  72663. });
  72664. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  72665. /** Gets or sets value of X button */
  72666. get: function () {
  72667. return this._buttonX;
  72668. },
  72669. set: function (value) {
  72670. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  72671. },
  72672. enumerable: true,
  72673. configurable: true
  72674. });
  72675. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  72676. /** Gets or sets value of Y button */
  72677. get: function () {
  72678. return this._buttonY;
  72679. },
  72680. set: function (value) {
  72681. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  72682. },
  72683. enumerable: true,
  72684. configurable: true
  72685. });
  72686. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  72687. /** Gets or sets value of Start button */
  72688. get: function () {
  72689. return this._buttonStart;
  72690. },
  72691. set: function (value) {
  72692. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  72693. },
  72694. enumerable: true,
  72695. configurable: true
  72696. });
  72697. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  72698. /** Gets or sets value of Back button */
  72699. get: function () {
  72700. return this._buttonBack;
  72701. },
  72702. set: function (value) {
  72703. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  72704. },
  72705. enumerable: true,
  72706. configurable: true
  72707. });
  72708. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  72709. /** Gets or sets value of Left button */
  72710. get: function () {
  72711. return this._buttonLB;
  72712. },
  72713. set: function (value) {
  72714. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  72715. },
  72716. enumerable: true,
  72717. configurable: true
  72718. });
  72719. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  72720. /** Gets or sets value of Right button */
  72721. get: function () {
  72722. return this._buttonRB;
  72723. },
  72724. set: function (value) {
  72725. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  72726. },
  72727. enumerable: true,
  72728. configurable: true
  72729. });
  72730. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  72731. /** Gets or sets value of left stick */
  72732. get: function () {
  72733. return this._buttonLeftStick;
  72734. },
  72735. set: function (value) {
  72736. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  72737. },
  72738. enumerable: true,
  72739. configurable: true
  72740. });
  72741. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  72742. /** Gets or sets value of right stick */
  72743. get: function () {
  72744. return this._buttonRightStick;
  72745. },
  72746. set: function (value) {
  72747. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  72748. },
  72749. enumerable: true,
  72750. configurable: true
  72751. });
  72752. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  72753. /** Gets or sets value of DPad up */
  72754. get: function () {
  72755. return this._dPadUp;
  72756. },
  72757. set: function (value) {
  72758. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  72759. },
  72760. enumerable: true,
  72761. configurable: true
  72762. });
  72763. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  72764. /** Gets or sets value of DPad down */
  72765. get: function () {
  72766. return this._dPadDown;
  72767. },
  72768. set: function (value) {
  72769. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  72770. },
  72771. enumerable: true,
  72772. configurable: true
  72773. });
  72774. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  72775. /** Gets or sets value of DPad left */
  72776. get: function () {
  72777. return this._dPadLeft;
  72778. },
  72779. set: function (value) {
  72780. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  72781. },
  72782. enumerable: true,
  72783. configurable: true
  72784. });
  72785. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  72786. /** Gets or sets value of DPad right */
  72787. get: function () {
  72788. return this._dPadRight;
  72789. },
  72790. set: function (value) {
  72791. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  72792. },
  72793. enumerable: true,
  72794. configurable: true
  72795. });
  72796. /**
  72797. * Force the gamepad to synchronize with device values
  72798. */
  72799. Xbox360Pad.prototype.update = function () {
  72800. _super.prototype.update.call(this);
  72801. if (this._isXboxOnePad) {
  72802. this.buttonA = this.browserGamepad.buttons[0].value;
  72803. this.buttonB = this.browserGamepad.buttons[1].value;
  72804. this.buttonX = this.browserGamepad.buttons[2].value;
  72805. this.buttonY = this.browserGamepad.buttons[3].value;
  72806. this.buttonLB = this.browserGamepad.buttons[4].value;
  72807. this.buttonRB = this.browserGamepad.buttons[5].value;
  72808. this.leftTrigger = this.browserGamepad.axes[2];
  72809. this.rightTrigger = this.browserGamepad.axes[5];
  72810. this.buttonBack = this.browserGamepad.buttons[9].value;
  72811. this.buttonStart = this.browserGamepad.buttons[8].value;
  72812. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  72813. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  72814. this.dPadUp = this.browserGamepad.buttons[11].value;
  72815. this.dPadDown = this.browserGamepad.buttons[12].value;
  72816. this.dPadLeft = this.browserGamepad.buttons[13].value;
  72817. this.dPadRight = this.browserGamepad.buttons[14].value;
  72818. }
  72819. else {
  72820. this.buttonA = this.browserGamepad.buttons[0].value;
  72821. this.buttonB = this.browserGamepad.buttons[1].value;
  72822. this.buttonX = this.browserGamepad.buttons[2].value;
  72823. this.buttonY = this.browserGamepad.buttons[3].value;
  72824. this.buttonLB = this.browserGamepad.buttons[4].value;
  72825. this.buttonRB = this.browserGamepad.buttons[5].value;
  72826. this.leftTrigger = this.browserGamepad.buttons[6].value;
  72827. this.rightTrigger = this.browserGamepad.buttons[7].value;
  72828. this.buttonBack = this.browserGamepad.buttons[8].value;
  72829. this.buttonStart = this.browserGamepad.buttons[9].value;
  72830. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  72831. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  72832. this.dPadUp = this.browserGamepad.buttons[12].value;
  72833. this.dPadDown = this.browserGamepad.buttons[13].value;
  72834. this.dPadLeft = this.browserGamepad.buttons[14].value;
  72835. this.dPadRight = this.browserGamepad.buttons[15].value;
  72836. }
  72837. };
  72838. Xbox360Pad.prototype.dispose = function () {
  72839. _super.prototype.dispose.call(this);
  72840. this.onButtonDownObservable.clear();
  72841. this.onButtonUpObservable.clear();
  72842. this.onPadDownObservable.clear();
  72843. this.onPadUpObservable.clear();
  72844. };
  72845. return Xbox360Pad;
  72846. }(BABYLON.Gamepad));
  72847. BABYLON.Xbox360Pad = Xbox360Pad;
  72848. })(BABYLON || (BABYLON = {}));
  72849. //# sourceMappingURL=babylon.xboxGamepad.js.map
  72850. var BABYLON;
  72851. (function (BABYLON) {
  72852. /**
  72853. * Defines the types of pose enabled controllers that are supported
  72854. */
  72855. var PoseEnabledControllerType;
  72856. (function (PoseEnabledControllerType) {
  72857. /**
  72858. * HTC Vive
  72859. */
  72860. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  72861. /**
  72862. * Oculus Rift
  72863. */
  72864. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  72865. /**
  72866. * Windows mixed reality
  72867. */
  72868. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  72869. /**
  72870. * Samsung gear VR
  72871. */
  72872. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  72873. /**
  72874. * Google Daydream
  72875. */
  72876. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  72877. /**
  72878. * Generic
  72879. */
  72880. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  72881. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  72882. /**
  72883. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72884. */
  72885. var PoseEnabledControllerHelper = /** @class */ (function () {
  72886. function PoseEnabledControllerHelper() {
  72887. }
  72888. /**
  72889. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  72890. * @param vrGamepad the gamepad to initialized
  72891. * @returns a vr controller of the type the gamepad identified as
  72892. */
  72893. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  72894. // Oculus Touch
  72895. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  72896. return new BABYLON.OculusTouchController(vrGamepad);
  72897. }
  72898. // Windows Mixed Reality controllers
  72899. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  72900. return new BABYLON.WindowsMotionController(vrGamepad);
  72901. }
  72902. // HTC Vive
  72903. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  72904. return new BABYLON.ViveController(vrGamepad);
  72905. }
  72906. // Samsung/Oculus Gear VR or Oculus Go
  72907. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  72908. return new BABYLON.GearVRController(vrGamepad);
  72909. }
  72910. // Google Daydream
  72911. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  72912. return new BABYLON.DaydreamController(vrGamepad);
  72913. }
  72914. // Generic
  72915. else {
  72916. return new BABYLON.GenericController(vrGamepad);
  72917. }
  72918. };
  72919. return PoseEnabledControllerHelper;
  72920. }());
  72921. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  72922. /**
  72923. * Defines the PoseEnabledController object that contains state of a vr capable controller
  72924. */
  72925. var PoseEnabledController = /** @class */ (function (_super) {
  72926. __extends(PoseEnabledController, _super);
  72927. /**
  72928. * Creates a new PoseEnabledController from a gamepad
  72929. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  72930. */
  72931. function PoseEnabledController(browserGamepad) {
  72932. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  72933. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72934. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72935. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  72936. /**
  72937. * The device position in babylon space
  72938. */
  72939. _this.devicePosition = BABYLON.Vector3.Zero();
  72940. /**
  72941. * The device rotation in babylon space
  72942. */
  72943. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  72944. /**
  72945. * The scale factor of the device in babylon space
  72946. */
  72947. _this.deviceScaleFactor = 1;
  72948. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  72949. /**
  72950. * Internal, matrix used to convert room space to babylon space
  72951. */
  72952. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72953. /**
  72954. * Node to be used when casting a ray from the controller
  72955. */
  72956. _this._pointingPoseNode = null;
  72957. _this._workingMatrix = BABYLON.Matrix.Identity();
  72958. /**
  72959. * @hidden
  72960. */
  72961. _this._meshAttachedObservable = new BABYLON.Observable();
  72962. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  72963. _this.controllerType = PoseEnabledControllerType.GENERIC;
  72964. _this.position = BABYLON.Vector3.Zero();
  72965. _this.rotationQuaternion = new BABYLON.Quaternion();
  72966. _this._calculatedPosition = BABYLON.Vector3.Zero();
  72967. _this._calculatedRotation = new BABYLON.Quaternion();
  72968. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  72969. return _this;
  72970. }
  72971. /**
  72972. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  72973. */
  72974. PoseEnabledController.prototype.update = function () {
  72975. _super.prototype.update.call(this);
  72976. this._updatePoseAndMesh();
  72977. };
  72978. /**
  72979. * Updates only the pose device and mesh without doing any button event checking
  72980. */
  72981. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  72982. var pose = this.browserGamepad.pose;
  72983. this.updateFromDevice(pose);
  72984. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  72985. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72986. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72987. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72988. if (this._mesh) {
  72989. this._mesh.position.copyFrom(this.devicePosition);
  72990. if (this._mesh.rotationQuaternion) {
  72991. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72992. }
  72993. }
  72994. };
  72995. /**
  72996. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72997. * @param poseData raw pose fromthe device
  72998. */
  72999. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  73000. if (poseData) {
  73001. this.rawPose = poseData;
  73002. if (poseData.position) {
  73003. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  73004. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  73005. this._deviceRoomPosition.z *= -1;
  73006. }
  73007. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  73008. this._calculatedPosition.addInPlace(this.position);
  73009. }
  73010. var pose = this.rawPose;
  73011. if (poseData.orientation && pose.orientation) {
  73012. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  73013. if (this._mesh) {
  73014. if (this._mesh.getScene().useRightHandedSystem) {
  73015. this._deviceRoomRotationQuaternion.z *= -1;
  73016. this._deviceRoomRotationQuaternion.w *= -1;
  73017. }
  73018. else {
  73019. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  73020. }
  73021. }
  73022. // if the camera is set, rotate to the camera's rotation
  73023. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  73024. }
  73025. }
  73026. };
  73027. /**
  73028. * Attaches a mesh to the controller
  73029. * @param mesh the mesh to be attached
  73030. */
  73031. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  73032. if (this._mesh) {
  73033. this._mesh.parent = null;
  73034. }
  73035. this._mesh = mesh;
  73036. if (this._poseControlledCamera) {
  73037. this._mesh.parent = this._poseControlledCamera;
  73038. }
  73039. if (!this._mesh.rotationQuaternion) {
  73040. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  73041. }
  73042. // 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
  73043. this._updatePoseAndMesh();
  73044. if (this._pointingPoseNode) {
  73045. var parents = [];
  73046. var obj = this._pointingPoseNode;
  73047. while (obj.parent) {
  73048. parents.push(obj.parent);
  73049. obj = obj.parent;
  73050. }
  73051. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  73052. }
  73053. this._meshAttachedObservable.notifyObservers(mesh);
  73054. };
  73055. /**
  73056. * Attaches the controllers mesh to a camera
  73057. * @param camera the camera the mesh should be attached to
  73058. */
  73059. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  73060. this._poseControlledCamera = camera;
  73061. if (this._mesh) {
  73062. this._mesh.parent = this._poseControlledCamera;
  73063. }
  73064. };
  73065. /**
  73066. * Disposes of the controller
  73067. */
  73068. PoseEnabledController.prototype.dispose = function () {
  73069. if (this._mesh) {
  73070. this._mesh.dispose();
  73071. }
  73072. this._mesh = null;
  73073. _super.prototype.dispose.call(this);
  73074. };
  73075. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  73076. /**
  73077. * The mesh that is attached to the controller
  73078. */
  73079. get: function () {
  73080. return this._mesh;
  73081. },
  73082. enumerable: true,
  73083. configurable: true
  73084. });
  73085. /**
  73086. * Gets the ray of the controller in the direction the controller is pointing
  73087. * @param length the length the resulting ray should be
  73088. * @returns a ray in the direction the controller is pointing
  73089. */
  73090. PoseEnabledController.prototype.getForwardRay = function (length) {
  73091. if (length === void 0) { length = 100; }
  73092. if (!this.mesh) {
  73093. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  73094. }
  73095. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  73096. var origin = m.getTranslation();
  73097. var forward = new BABYLON.Vector3(0, 0, -1);
  73098. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73099. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73100. return new BABYLON.Ray(origin, direction, length);
  73101. };
  73102. /**
  73103. * Name of the child mesh that can be used to cast a ray from the controller
  73104. */
  73105. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  73106. return PoseEnabledController;
  73107. }(BABYLON.Gamepad));
  73108. BABYLON.PoseEnabledController = PoseEnabledController;
  73109. })(BABYLON || (BABYLON = {}));
  73110. //# sourceMappingURL=babylon.poseEnabledController.js.map
  73111. var BABYLON;
  73112. (function (BABYLON) {
  73113. /**
  73114. * Defines the WebVRController object that represents controllers tracked in 3D space
  73115. */
  73116. var WebVRController = /** @class */ (function (_super) {
  73117. __extends(WebVRController, _super);
  73118. /**
  73119. * Creates a new WebVRController from a gamepad
  73120. * @param vrGamepad the gamepad that the WebVRController should be created from
  73121. */
  73122. function WebVRController(vrGamepad) {
  73123. var _this = _super.call(this, vrGamepad) || this;
  73124. // Observables
  73125. /**
  73126. * Fired when the trigger state has changed
  73127. */
  73128. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  73129. /**
  73130. * Fired when the main button state has changed
  73131. */
  73132. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  73133. /**
  73134. * Fired when the secondary button state has changed
  73135. */
  73136. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  73137. /**
  73138. * Fired when the pad state has changed
  73139. */
  73140. _this.onPadStateChangedObservable = new BABYLON.Observable();
  73141. /**
  73142. * Fired when controllers stick values have changed
  73143. */
  73144. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  73145. /**
  73146. * X and Y axis corrisponding to the controllers joystick
  73147. */
  73148. _this.pad = { x: 0, y: 0 };
  73149. // avoid GC, store state in a tmp object
  73150. _this._changes = {
  73151. pressChanged: false,
  73152. touchChanged: false,
  73153. valueChanged: false,
  73154. changed: false
  73155. };
  73156. _this._buttons = new Array(vrGamepad.buttons.length);
  73157. _this.hand = vrGamepad.hand;
  73158. return _this;
  73159. }
  73160. /**
  73161. * Fired when a controller button's state has changed
  73162. * @param callback the callback containing the button that was modified
  73163. */
  73164. WebVRController.prototype.onButtonStateChange = function (callback) {
  73165. this._onButtonStateChange = callback;
  73166. };
  73167. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  73168. /**
  73169. * The default controller model for the controller
  73170. */
  73171. get: function () {
  73172. return this._defaultModel;
  73173. },
  73174. enumerable: true,
  73175. configurable: true
  73176. });
  73177. /**
  73178. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  73179. */
  73180. WebVRController.prototype.update = function () {
  73181. _super.prototype.update.call(this);
  73182. for (var index = 0; index < this._buttons.length; index++) {
  73183. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  73184. }
  73185. ;
  73186. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  73187. this.pad.x = this.leftStick.x;
  73188. this.pad.y = this.leftStick.y;
  73189. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  73190. }
  73191. };
  73192. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  73193. if (!newState) {
  73194. newState = {
  73195. pressed: false,
  73196. touched: false,
  73197. value: 0
  73198. };
  73199. }
  73200. if (!currentState) {
  73201. this._buttons[buttonIndex] = {
  73202. pressed: newState.pressed,
  73203. touched: newState.touched,
  73204. value: newState.value
  73205. };
  73206. return;
  73207. }
  73208. this._checkChanges(newState, currentState);
  73209. if (this._changes.changed) {
  73210. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  73211. this._handleButtonChange(buttonIndex, newState, this._changes);
  73212. }
  73213. this._buttons[buttonIndex].pressed = newState.pressed;
  73214. this._buttons[buttonIndex].touched = newState.touched;
  73215. // oculus triggers are never 0, thou not touched.
  73216. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  73217. };
  73218. WebVRController.prototype._checkChanges = function (newState, currentState) {
  73219. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  73220. this._changes.touchChanged = newState.touched !== currentState.touched;
  73221. this._changes.valueChanged = newState.value !== currentState.value;
  73222. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  73223. return this._changes;
  73224. };
  73225. /**
  73226. * Disposes of th webVRCOntroller
  73227. */
  73228. WebVRController.prototype.dispose = function () {
  73229. _super.prototype.dispose.call(this);
  73230. this.onTriggerStateChangedObservable.clear();
  73231. this.onMainButtonStateChangedObservable.clear();
  73232. this.onSecondaryButtonStateChangedObservable.clear();
  73233. this.onPadStateChangedObservable.clear();
  73234. this.onPadValuesChangedObservable.clear();
  73235. };
  73236. return WebVRController;
  73237. }(BABYLON.PoseEnabledController));
  73238. BABYLON.WebVRController = WebVRController;
  73239. })(BABYLON || (BABYLON = {}));
  73240. //# sourceMappingURL=babylon.webVRController.js.map
  73241. var BABYLON;
  73242. (function (BABYLON) {
  73243. /**
  73244. * Oculus Touch Controller
  73245. */
  73246. var OculusTouchController = /** @class */ (function (_super) {
  73247. __extends(OculusTouchController, _super);
  73248. /**
  73249. * Creates a new OculusTouchController from a gamepad
  73250. * @param vrGamepad the gamepad that the controller should be created from
  73251. */
  73252. function OculusTouchController(vrGamepad) {
  73253. var _this = _super.call(this, vrGamepad) || this;
  73254. /**
  73255. * Fired when the secondary trigger on this controller is modified
  73256. */
  73257. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  73258. /**
  73259. * Fired when the thumb rest on this controller is modified
  73260. */
  73261. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  73262. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  73263. return _this;
  73264. }
  73265. /**
  73266. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73267. * @param scene scene in which to add meshes
  73268. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73269. */
  73270. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73271. var _this = this;
  73272. var meshName;
  73273. // Hand
  73274. if (this.hand === 'left') {
  73275. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  73276. }
  73277. else { // Right is the default if no hand is specified
  73278. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  73279. }
  73280. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  73281. /*
  73282. Parent Mesh name: oculus_touch_left
  73283. - body
  73284. - trigger
  73285. - thumbstick
  73286. - grip
  73287. - button_y
  73288. - button_x
  73289. - button_enter
  73290. */
  73291. _this._defaultModel = newMeshes[1];
  73292. _this.attachToMesh(_this._defaultModel);
  73293. if (meshLoaded) {
  73294. meshLoaded(_this._defaultModel);
  73295. }
  73296. });
  73297. };
  73298. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  73299. /**
  73300. * Fired when the A button on this controller is modified
  73301. */
  73302. get: function () {
  73303. if (this.hand === 'right') {
  73304. return this.onMainButtonStateChangedObservable;
  73305. }
  73306. else {
  73307. throw new Error('No A button on left hand');
  73308. }
  73309. },
  73310. enumerable: true,
  73311. configurable: true
  73312. });
  73313. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  73314. /**
  73315. * Fired when the B button on this controller is modified
  73316. */
  73317. get: function () {
  73318. if (this.hand === 'right') {
  73319. return this.onSecondaryButtonStateChangedObservable;
  73320. }
  73321. else {
  73322. throw new Error('No B button on left hand');
  73323. }
  73324. },
  73325. enumerable: true,
  73326. configurable: true
  73327. });
  73328. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  73329. /**
  73330. * Fired when the X button on this controller is modified
  73331. */
  73332. get: function () {
  73333. if (this.hand === 'left') {
  73334. return this.onMainButtonStateChangedObservable;
  73335. }
  73336. else {
  73337. throw new Error('No X button on right hand');
  73338. }
  73339. },
  73340. enumerable: true,
  73341. configurable: true
  73342. });
  73343. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  73344. /**
  73345. * Fired when the Y button on this controller is modified
  73346. */
  73347. get: function () {
  73348. if (this.hand === 'left') {
  73349. return this.onSecondaryButtonStateChangedObservable;
  73350. }
  73351. else {
  73352. throw new Error('No Y button on right hand');
  73353. }
  73354. },
  73355. enumerable: true,
  73356. configurable: true
  73357. });
  73358. /**
  73359. * Called once for each button that changed state since the last frame
  73360. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  73361. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  73362. * 2) secondary trigger (same)
  73363. * 3) A (right) X (left), touch, pressed = value
  73364. * 4) B / Y
  73365. * 5) thumb rest
  73366. * @param buttonIdx Which button index changed
  73367. * @param state New state of the button
  73368. * @param changes Which properties on the state changed since last frame
  73369. */
  73370. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73371. var notifyObject = state; //{ state: state, changes: changes };
  73372. var triggerDirection = this.hand === 'right' ? -1 : 1;
  73373. switch (buttonIdx) {
  73374. case 0:
  73375. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73376. return;
  73377. case 1: // index trigger
  73378. if (this._defaultModel) {
  73379. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  73380. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  73381. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  73382. }
  73383. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73384. return;
  73385. case 2: // secondary trigger
  73386. if (this._defaultModel) {
  73387. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  73388. }
  73389. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  73390. return;
  73391. case 3:
  73392. if (this._defaultModel) {
  73393. if (notifyObject.pressed) {
  73394. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  73395. }
  73396. else {
  73397. (this._defaultModel.getChildren()[1]).position.y = 0;
  73398. }
  73399. }
  73400. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73401. return;
  73402. case 4:
  73403. if (this._defaultModel) {
  73404. if (notifyObject.pressed) {
  73405. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73406. }
  73407. else {
  73408. (this._defaultModel.getChildren()[2]).position.y = 0;
  73409. }
  73410. }
  73411. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73412. return;
  73413. case 5:
  73414. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  73415. return;
  73416. }
  73417. };
  73418. /**
  73419. * Base Url for the controller model.
  73420. */
  73421. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  73422. /**
  73423. * File name for the left controller model.
  73424. */
  73425. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  73426. /**
  73427. * File name for the right controller model.
  73428. */
  73429. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  73430. return OculusTouchController;
  73431. }(BABYLON.WebVRController));
  73432. BABYLON.OculusTouchController = OculusTouchController;
  73433. })(BABYLON || (BABYLON = {}));
  73434. //# sourceMappingURL=babylon.oculusTouchController.js.map
  73435. var BABYLON;
  73436. (function (BABYLON) {
  73437. /**
  73438. * Vive Controller
  73439. */
  73440. var ViveController = /** @class */ (function (_super) {
  73441. __extends(ViveController, _super);
  73442. /**
  73443. * Creates a new ViveController from a gamepad
  73444. * @param vrGamepad the gamepad that the controller should be created from
  73445. */
  73446. function ViveController(vrGamepad) {
  73447. var _this = _super.call(this, vrGamepad) || this;
  73448. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  73449. _this._invertLeftStickY = true;
  73450. return _this;
  73451. }
  73452. /**
  73453. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73454. * @param scene scene in which to add meshes
  73455. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73456. */
  73457. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73458. var _this = this;
  73459. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  73460. /*
  73461. Parent Mesh name: ViveWand
  73462. - body
  73463. - r_gripper
  73464. - l_gripper
  73465. - menu_button
  73466. - system_button
  73467. - trackpad
  73468. - trigger
  73469. - LED
  73470. */
  73471. _this._defaultModel = newMeshes[1];
  73472. _this.attachToMesh(_this._defaultModel);
  73473. if (meshLoaded) {
  73474. meshLoaded(_this._defaultModel);
  73475. }
  73476. });
  73477. };
  73478. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  73479. /**
  73480. * Fired when the left button on this controller is modified
  73481. */
  73482. get: function () {
  73483. return this.onMainButtonStateChangedObservable;
  73484. },
  73485. enumerable: true,
  73486. configurable: true
  73487. });
  73488. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  73489. /**
  73490. * Fired when the right button on this controller is modified
  73491. */
  73492. get: function () {
  73493. return this.onMainButtonStateChangedObservable;
  73494. },
  73495. enumerable: true,
  73496. configurable: true
  73497. });
  73498. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  73499. /**
  73500. * Fired when the menu button on this controller is modified
  73501. */
  73502. get: function () {
  73503. return this.onSecondaryButtonStateChangedObservable;
  73504. },
  73505. enumerable: true,
  73506. configurable: true
  73507. });
  73508. /**
  73509. * Called once for each button that changed state since the last frame
  73510. * Vive mapping:
  73511. * 0: touchpad
  73512. * 1: trigger
  73513. * 2: left AND right buttons
  73514. * 3: menu button
  73515. * @param buttonIdx Which button index changed
  73516. * @param state New state of the button
  73517. * @param changes Which properties on the state changed since last frame
  73518. */
  73519. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73520. var notifyObject = state; //{ state: state, changes: changes };
  73521. switch (buttonIdx) {
  73522. case 0:
  73523. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  73524. return;
  73525. case 1: // index trigger
  73526. if (this._defaultModel) {
  73527. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  73528. }
  73529. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  73530. return;
  73531. case 2: // left AND right button
  73532. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  73533. return;
  73534. case 3:
  73535. if (this._defaultModel) {
  73536. if (notifyObject.pressed) {
  73537. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  73538. }
  73539. else {
  73540. (this._defaultModel.getChildren()[2]).position.y = 0;
  73541. }
  73542. }
  73543. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  73544. return;
  73545. }
  73546. };
  73547. /**
  73548. * Base Url for the controller model.
  73549. */
  73550. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  73551. /**
  73552. * File name for the controller model.
  73553. */
  73554. ViveController.MODEL_FILENAME = 'wand.babylon';
  73555. return ViveController;
  73556. }(BABYLON.WebVRController));
  73557. BABYLON.ViveController = ViveController;
  73558. })(BABYLON || (BABYLON = {}));
  73559. //# sourceMappingURL=babylon.viveController.js.map
  73560. var BABYLON;
  73561. (function (BABYLON) {
  73562. /**
  73563. * Generic Controller
  73564. */
  73565. var GenericController = /** @class */ (function (_super) {
  73566. __extends(GenericController, _super);
  73567. /**
  73568. * Creates a new GenericController from a gamepad
  73569. * @param vrGamepad the gamepad that the controller should be created from
  73570. */
  73571. function GenericController(vrGamepad) {
  73572. return _super.call(this, vrGamepad) || this;
  73573. }
  73574. /**
  73575. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73576. * @param scene scene in which to add meshes
  73577. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73578. */
  73579. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73580. var _this = this;
  73581. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  73582. _this._defaultModel = newMeshes[1];
  73583. _this.attachToMesh(_this._defaultModel);
  73584. if (meshLoaded) {
  73585. meshLoaded(_this._defaultModel);
  73586. }
  73587. });
  73588. };
  73589. /**
  73590. * Called once for each button that changed state since the last frame
  73591. * @param buttonIdx Which button index changed
  73592. * @param state New state of the button
  73593. * @param changes Which properties on the state changed since last frame
  73594. */
  73595. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73596. console.log("Button id: " + buttonIdx + "state: ");
  73597. console.dir(state);
  73598. };
  73599. /**
  73600. * Base Url for the controller model.
  73601. */
  73602. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73603. /**
  73604. * File name for the controller model.
  73605. */
  73606. GenericController.MODEL_FILENAME = 'generic.babylon';
  73607. return GenericController;
  73608. }(BABYLON.WebVRController));
  73609. BABYLON.GenericController = GenericController;
  73610. })(BABYLON || (BABYLON = {}));
  73611. //# sourceMappingURL=babylon.genericController.js.map
  73612. var BABYLON;
  73613. (function (BABYLON) {
  73614. /**
  73615. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  73616. */
  73617. var LoadedMeshInfo = /** @class */ (function () {
  73618. function LoadedMeshInfo() {
  73619. /**
  73620. * Map of the button meshes contained in the controller
  73621. */
  73622. this.buttonMeshes = {};
  73623. /**
  73624. * Map of the axis meshes contained in the controller
  73625. */
  73626. this.axisMeshes = {};
  73627. }
  73628. return LoadedMeshInfo;
  73629. }());
  73630. /**
  73631. * Defines the WindowsMotionController object that the state of the windows motion controller
  73632. */
  73633. var WindowsMotionController = /** @class */ (function (_super) {
  73634. __extends(WindowsMotionController, _super);
  73635. /**
  73636. * Creates a new WindowsMotionController from a gamepad
  73637. * @param vrGamepad the gamepad that the controller should be created from
  73638. */
  73639. function WindowsMotionController(vrGamepad) {
  73640. var _this = _super.call(this, vrGamepad) || this;
  73641. _this._mapping = {
  73642. // Semantic button names
  73643. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  73644. // A mapping of the button name to glTF model node name
  73645. // that should be transformed by button value.
  73646. buttonMeshNames: {
  73647. 'trigger': 'SELECT',
  73648. 'menu': 'MENU',
  73649. 'grip': 'GRASP',
  73650. 'thumbstick': 'THUMBSTICK_PRESS',
  73651. 'trackpad': 'TOUCHPAD_PRESS'
  73652. },
  73653. // This mapping is used to translate from the Motion Controller to Babylon semantics
  73654. buttonObservableNames: {
  73655. 'trigger': 'onTriggerStateChangedObservable',
  73656. 'menu': 'onSecondaryButtonStateChangedObservable',
  73657. 'grip': 'onMainButtonStateChangedObservable',
  73658. 'thumbstick': 'onPadStateChangedObservable',
  73659. 'trackpad': 'onTrackpadChangedObservable'
  73660. },
  73661. // A mapping of the axis name to glTF model node name
  73662. // that should be transformed by axis value.
  73663. // This array mirrors the browserGamepad.axes array, such that
  73664. // the mesh corresponding to axis 0 is in this array index 0.
  73665. axisMeshNames: [
  73666. 'THUMBSTICK_X',
  73667. 'THUMBSTICK_Y',
  73668. 'TOUCHPAD_TOUCH_X',
  73669. 'TOUCHPAD_TOUCH_Y'
  73670. ],
  73671. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  73672. };
  73673. /**
  73674. * Fired when the trackpad on this controller is clicked
  73675. */
  73676. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  73677. /**
  73678. * Fired when the trackpad on this controller is modified
  73679. */
  73680. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  73681. /**
  73682. * The current x and y values of this controller's trackpad
  73683. */
  73684. _this.trackpad = { x: 0, y: 0 };
  73685. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  73686. _this._loadedMeshInfo = null;
  73687. return _this;
  73688. }
  73689. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  73690. /**
  73691. * Fired when the trigger on this controller is modified
  73692. */
  73693. get: function () {
  73694. return this.onTriggerStateChangedObservable;
  73695. },
  73696. enumerable: true,
  73697. configurable: true
  73698. });
  73699. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  73700. /**
  73701. * Fired when the menu button on this controller is modified
  73702. */
  73703. get: function () {
  73704. return this.onSecondaryButtonStateChangedObservable;
  73705. },
  73706. enumerable: true,
  73707. configurable: true
  73708. });
  73709. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  73710. /**
  73711. * Fired when the grip button on this controller is modified
  73712. */
  73713. get: function () {
  73714. return this.onMainButtonStateChangedObservable;
  73715. },
  73716. enumerable: true,
  73717. configurable: true
  73718. });
  73719. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  73720. /**
  73721. * Fired when the thumbstick button on this controller is modified
  73722. */
  73723. get: function () {
  73724. return this.onPadStateChangedObservable;
  73725. },
  73726. enumerable: true,
  73727. configurable: true
  73728. });
  73729. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  73730. /**
  73731. * Fired when the touchpad button on this controller is modified
  73732. */
  73733. get: function () {
  73734. return this.onTrackpadChangedObservable;
  73735. },
  73736. enumerable: true,
  73737. configurable: true
  73738. });
  73739. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  73740. /**
  73741. * Fired when the touchpad values on this controller are modified
  73742. */
  73743. get: function () {
  73744. return this.onTrackpadValuesChangedObservable;
  73745. },
  73746. enumerable: true,
  73747. configurable: true
  73748. });
  73749. WindowsMotionController.prototype._updateTrackpad = function () {
  73750. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  73751. this.trackpad.x = this.browserGamepad["axes"][2];
  73752. this.trackpad.y = this.browserGamepad["axes"][3];
  73753. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  73754. }
  73755. };
  73756. /**
  73757. * Called once per frame by the engine.
  73758. */
  73759. WindowsMotionController.prototype.update = function () {
  73760. _super.prototype.update.call(this);
  73761. if (this.browserGamepad.axes) {
  73762. this._updateTrackpad();
  73763. // Only need to animate axes if there is a loaded mesh
  73764. if (this._loadedMeshInfo) {
  73765. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  73766. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  73767. }
  73768. }
  73769. }
  73770. };
  73771. /**
  73772. * Called once for each button that changed state since the last frame
  73773. * @param buttonIdx Which button index changed
  73774. * @param state New state of the button
  73775. * @param changes Which properties on the state changed since last frame
  73776. */
  73777. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73778. var buttonName = this._mapping.buttons[buttonIdx];
  73779. if (!buttonName) {
  73780. return;
  73781. }
  73782. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  73783. this._updateTrackpad();
  73784. // Only emit events for buttons that we know how to map from index to name
  73785. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  73786. if (observable) {
  73787. observable.notifyObservers(state);
  73788. }
  73789. this._lerpButtonTransform(buttonName, state.value);
  73790. };
  73791. /**
  73792. * Moves the buttons on the controller mesh based on their current state
  73793. * @param buttonName the name of the button to move
  73794. * @param buttonValue the value of the button which determines the buttons new position
  73795. */
  73796. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  73797. // If there is no loaded mesh, there is nothing to transform.
  73798. if (!this._loadedMeshInfo) {
  73799. return;
  73800. }
  73801. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  73802. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73803. return;
  73804. }
  73805. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  73806. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  73807. };
  73808. /**
  73809. * Moves the axis on the controller mesh based on its current state
  73810. * @param axis the index of the axis
  73811. * @param axisValue the value of the axis which determines the meshes new position
  73812. * @hidden
  73813. */
  73814. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  73815. if (!this._loadedMeshInfo) {
  73816. return;
  73817. }
  73818. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  73819. if (!meshInfo) {
  73820. return;
  73821. }
  73822. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  73823. return;
  73824. }
  73825. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  73826. var lerpValue = axisValue * 0.5 + 0.5;
  73827. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  73828. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  73829. };
  73830. /**
  73831. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73832. * @param scene scene in which to add meshes
  73833. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73834. */
  73835. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  73836. var _this = this;
  73837. if (forceDefault === void 0) { forceDefault = false; }
  73838. var path;
  73839. var filename;
  73840. // Checking if GLB loader is present
  73841. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  73842. // Determine the device specific folder based on the ID suffix
  73843. var device = 'default';
  73844. if (this.id && !forceDefault) {
  73845. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  73846. device = ((match && match[0]) || device);
  73847. }
  73848. // Hand
  73849. if (this.hand === 'left') {
  73850. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  73851. }
  73852. else { // Right is the default if no hand is specified
  73853. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  73854. }
  73855. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  73856. }
  73857. else {
  73858. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  73859. path = BABYLON.GenericController.MODEL_BASE_URL;
  73860. filename = BABYLON.GenericController.MODEL_FILENAME;
  73861. }
  73862. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  73863. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  73864. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  73865. if (!_this._loadedMeshInfo) {
  73866. return;
  73867. }
  73868. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  73869. _this.attachToMesh(_this._defaultModel);
  73870. if (meshLoaded) {
  73871. meshLoaded(_this._defaultModel);
  73872. }
  73873. }, null, function (scene, message) {
  73874. BABYLON.Tools.Log(message);
  73875. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  73876. if (!forceDefault) {
  73877. _this.initControllerMesh(scene, meshLoaded, true);
  73878. }
  73879. });
  73880. };
  73881. /**
  73882. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  73883. * can be transformed by button presses and axes values, based on this._mapping.
  73884. *
  73885. * @param scene scene in which the meshes exist
  73886. * @param meshes list of meshes that make up the controller model to process
  73887. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  73888. */
  73889. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  73890. var loadedMeshInfo = null;
  73891. // Create a new mesh to contain the glTF hierarchy
  73892. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  73893. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  73894. var childMesh = null;
  73895. for (var i = 0; i < meshes.length; i++) {
  73896. var mesh = meshes[i];
  73897. if (!mesh.parent) {
  73898. // Exclude controller meshes from picking results
  73899. mesh.isPickable = false;
  73900. // Handle root node, attach to the new parentMesh
  73901. childMesh = mesh;
  73902. break;
  73903. }
  73904. }
  73905. if (childMesh) {
  73906. childMesh.setParent(parentMesh);
  73907. // Create our mesh info. Note that this method will always return non-null.
  73908. loadedMeshInfo = this.createMeshInfo(parentMesh);
  73909. }
  73910. else {
  73911. BABYLON.Tools.Warn('Could not find root node in model file.');
  73912. }
  73913. return loadedMeshInfo;
  73914. };
  73915. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  73916. var loadedMeshInfo = new LoadedMeshInfo();
  73917. var i;
  73918. loadedMeshInfo.rootNode = rootNode;
  73919. // Reset the caches
  73920. loadedMeshInfo.buttonMeshes = {};
  73921. loadedMeshInfo.axisMeshes = {};
  73922. // Button Meshes
  73923. for (i = 0; i < this._mapping.buttons.length; i++) {
  73924. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  73925. if (!buttonMeshName) {
  73926. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  73927. continue;
  73928. }
  73929. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  73930. if (!buttonMesh) {
  73931. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  73932. continue;
  73933. }
  73934. var buttonMeshInfo = {
  73935. index: i,
  73936. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  73937. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  73938. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  73939. };
  73940. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  73941. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  73942. }
  73943. else {
  73944. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  73945. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  73946. '(VALUE: ' + !!buttonMeshInfo.value +
  73947. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  73948. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  73949. ')');
  73950. }
  73951. }
  73952. // Axis Meshes
  73953. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  73954. var axisMeshName = this._mapping.axisMeshNames[i];
  73955. if (!axisMeshName) {
  73956. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  73957. continue;
  73958. }
  73959. var axisMesh = getChildByName(rootNode, axisMeshName);
  73960. if (!axisMesh) {
  73961. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  73962. continue;
  73963. }
  73964. var axisMeshInfo = {
  73965. index: i,
  73966. value: getImmediateChildByName(axisMesh, 'VALUE'),
  73967. min: getImmediateChildByName(axisMesh, 'MIN'),
  73968. max: getImmediateChildByName(axisMesh, 'MAX')
  73969. };
  73970. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  73971. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  73972. }
  73973. else {
  73974. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  73975. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  73976. '(VALUE: ' + !!axisMeshInfo.value +
  73977. ', MIN: ' + !!axisMeshInfo.min +
  73978. ', MAX:' + !!axisMeshInfo.max +
  73979. ')');
  73980. }
  73981. }
  73982. // Pointing Ray
  73983. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  73984. if (!loadedMeshInfo.pointingPoseNode) {
  73985. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73986. }
  73987. else {
  73988. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73989. }
  73990. return loadedMeshInfo;
  73991. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73992. function getChildByName(node, name) {
  73993. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73994. }
  73995. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73996. function getImmediateChildByName(node, name) {
  73997. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73998. }
  73999. };
  74000. /**
  74001. * Gets the ray of the controller in the direction the controller is pointing
  74002. * @param length the length the resulting ray should be
  74003. * @returns a ray in the direction the controller is pointing
  74004. */
  74005. WindowsMotionController.prototype.getForwardRay = function (length) {
  74006. if (length === void 0) { length = 100; }
  74007. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  74008. return _super.prototype.getForwardRay.call(this, length);
  74009. }
  74010. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  74011. var origin = m.getTranslation();
  74012. var forward = new BABYLON.Vector3(0, 0, -1);
  74013. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74014. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74015. return new BABYLON.Ray(origin, direction, length);
  74016. };
  74017. /**
  74018. * Disposes of the controller
  74019. */
  74020. WindowsMotionController.prototype.dispose = function () {
  74021. _super.prototype.dispose.call(this);
  74022. this.onTrackpadChangedObservable.clear();
  74023. };
  74024. /**
  74025. * The base url used to load the left and right controller models
  74026. */
  74027. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  74028. /**
  74029. * The name of the left controller model file
  74030. */
  74031. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  74032. /**
  74033. * The name of the right controller model file
  74034. */
  74035. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  74036. /**
  74037. * The controller name prefix for this controller type
  74038. */
  74039. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  74040. /**
  74041. * The controller id pattern for this controller type
  74042. */
  74043. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  74044. return WindowsMotionController;
  74045. }(BABYLON.WebVRController));
  74046. BABYLON.WindowsMotionController = WindowsMotionController;
  74047. })(BABYLON || (BABYLON = {}));
  74048. //# sourceMappingURL=babylon.windowsMotionController.js.map
  74049. var BABYLON;
  74050. (function (BABYLON) {
  74051. /**
  74052. * Gear VR Controller
  74053. */
  74054. var GearVRController = /** @class */ (function (_super) {
  74055. __extends(GearVRController, _super);
  74056. /**
  74057. * Creates a new GearVRController from a gamepad
  74058. * @param vrGamepad the gamepad that the controller should be created from
  74059. */
  74060. function GearVRController(vrGamepad) {
  74061. var _this = _super.call(this, vrGamepad) || this;
  74062. _this._maxRotationDistFromHeadset = Math.PI / 5;
  74063. _this._draggedRoomRotation = 0;
  74064. _this._tmpVector = new BABYLON.Vector3();
  74065. _this._buttonIndexToObservableNameMap = [
  74066. 'onTrackpadChangedObservable',
  74067. 'onTriggerStateChangedObservable' // Trigger
  74068. ];
  74069. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  74070. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  74071. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  74072. return _this;
  74073. }
  74074. /**
  74075. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74076. * @param poseData raw pose fromthe device
  74077. */
  74078. GearVRController.prototype.updateFromDevice = function (poseData) {
  74079. _super.prototype.updateFromDevice.call(this, poseData);
  74080. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  74081. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  74082. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  74083. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  74084. // Find the radian distance away that the headset is from the controllers rotation
  74085. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  74086. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  74087. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  74088. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  74089. this._draggedRoomRotation += rotationAmount;
  74090. // Rotate controller around headset
  74091. var sin = Math.sin(-rotationAmount);
  74092. var cos = Math.cos(-rotationAmount);
  74093. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  74094. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  74095. }
  74096. }
  74097. }
  74098. };
  74099. /**
  74100. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74101. * @param scene scene in which to add meshes
  74102. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74103. */
  74104. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74105. var _this = this;
  74106. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  74107. // Offset the controller so it will rotate around the users wrist
  74108. var mesh = new BABYLON.Mesh("", scene);
  74109. newMeshes[1].parent = mesh;
  74110. newMeshes[1].position.z = -0.15;
  74111. _this._defaultModel = mesh;
  74112. _this.attachToMesh(_this._defaultModel);
  74113. if (meshLoaded) {
  74114. meshLoaded(_this._defaultModel);
  74115. }
  74116. });
  74117. };
  74118. /**
  74119. * Called once for each button that changed state since the last frame
  74120. * @param buttonIdx Which button index changed
  74121. * @param state New state of the button
  74122. * @param changes Which properties on the state changed since last frame
  74123. */
  74124. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74125. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  74126. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  74127. // Only emit events for buttons that we know how to map from index to observable
  74128. var observable = this[observableName];
  74129. if (observable) {
  74130. observable.notifyObservers(state);
  74131. }
  74132. }
  74133. };
  74134. /**
  74135. * Base Url for the controller model.
  74136. */
  74137. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74138. /**
  74139. * File name for the controller model.
  74140. */
  74141. GearVRController.MODEL_FILENAME = 'generic.babylon';
  74142. /**
  74143. * Gamepad Id prefix used to identify this controller.
  74144. */
  74145. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  74146. return GearVRController;
  74147. }(BABYLON.WebVRController));
  74148. BABYLON.GearVRController = GearVRController;
  74149. })(BABYLON || (BABYLON = {}));
  74150. //# sourceMappingURL=babylon.gearVRController.js.map
  74151. var BABYLON;
  74152. (function (BABYLON) {
  74153. /**
  74154. * Google Daydream controller
  74155. */
  74156. var DaydreamController = /** @class */ (function (_super) {
  74157. __extends(DaydreamController, _super);
  74158. /**
  74159. * Creates a new DaydreamController from a gamepad
  74160. * @param vrGamepad the gamepad that the controller should be created from
  74161. */
  74162. function DaydreamController(vrGamepad) {
  74163. var _this = _super.call(this, vrGamepad) || this;
  74164. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  74165. return _this;
  74166. }
  74167. /**
  74168. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74169. * @param scene scene in which to add meshes
  74170. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74171. */
  74172. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74173. var _this = this;
  74174. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  74175. _this._defaultModel = newMeshes[1];
  74176. _this.attachToMesh(_this._defaultModel);
  74177. if (meshLoaded) {
  74178. meshLoaded(_this._defaultModel);
  74179. }
  74180. });
  74181. };
  74182. /**
  74183. * Called once for each button that changed state since the last frame
  74184. * @param buttonIdx Which button index changed
  74185. * @param state New state of the button
  74186. * @param changes Which properties on the state changed since last frame
  74187. */
  74188. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74189. // Daydream controller only has 1 GamepadButton (on the trackpad).
  74190. if (buttonIdx === 0) {
  74191. var observable = this.onTriggerStateChangedObservable;
  74192. if (observable) {
  74193. observable.notifyObservers(state);
  74194. }
  74195. }
  74196. else {
  74197. // If the app or home buttons are ever made available
  74198. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  74199. }
  74200. };
  74201. /**
  74202. * Base Url for the controller model.
  74203. */
  74204. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74205. /**
  74206. * File name for the controller model.
  74207. */
  74208. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  74209. /**
  74210. * Gamepad Id prefix used to identify Daydream Controller.
  74211. */
  74212. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  74213. return DaydreamController;
  74214. }(BABYLON.WebVRController));
  74215. BABYLON.DaydreamController = DaydreamController;
  74216. })(BABYLON || (BABYLON = {}));
  74217. //# sourceMappingURL=babylon.daydreamController.js.map
  74218. var BABYLON;
  74219. (function (BABYLON) {
  74220. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  74221. get: function () {
  74222. if (!this._gamepadManager) {
  74223. this._gamepadManager = new BABYLON.GamepadManager(this);
  74224. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  74225. if (!component) {
  74226. component = new GamepadSystemSceneComponent(this);
  74227. this._addComponent(component);
  74228. }
  74229. }
  74230. return this._gamepadManager;
  74231. },
  74232. enumerable: true,
  74233. configurable: true
  74234. });
  74235. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  74236. this.add(new BABYLON.FreeCameraGamepadInput());
  74237. return this;
  74238. };
  74239. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  74240. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  74241. return this;
  74242. };
  74243. /**
  74244. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  74245. */
  74246. var GamepadSystemSceneComponent = /** @class */ (function () {
  74247. /**
  74248. * Creates a new instance of the component for the given scene
  74249. * @param scene Defines the scene to register the component in
  74250. */
  74251. function GamepadSystemSceneComponent(scene) {
  74252. /**
  74253. * The component name helpfull to identify the component in the list of scene components.
  74254. */
  74255. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  74256. this.scene = scene;
  74257. }
  74258. /**
  74259. * Registers the component in a given scene
  74260. */
  74261. GamepadSystemSceneComponent.prototype.register = function () {
  74262. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  74263. };
  74264. /**
  74265. * Rebuilds the elements related to this component in case of
  74266. * context lost for instance.
  74267. */
  74268. GamepadSystemSceneComponent.prototype.rebuild = function () {
  74269. // Nothing to do for gamepads
  74270. };
  74271. /**
  74272. * Disposes the component and the associated ressources
  74273. */
  74274. GamepadSystemSceneComponent.prototype.dispose = function () {
  74275. var gamepadManager = this.scene._gamepadManager;
  74276. if (gamepadManager) {
  74277. gamepadManager.dispose();
  74278. this.scene._gamepadManager = null;
  74279. }
  74280. };
  74281. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  74282. var gamepadManager = this.scene._gamepadManager;
  74283. if (gamepadManager && gamepadManager._isMonitoring) {
  74284. gamepadManager._checkGamepadsStatus();
  74285. }
  74286. };
  74287. return GamepadSystemSceneComponent;
  74288. }());
  74289. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  74290. })(BABYLON || (BABYLON = {}));
  74291. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  74292. var BABYLON;
  74293. (function (BABYLON) {
  74294. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  74295. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  74296. });
  74297. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  74298. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  74299. });
  74300. var FollowCamera = /** @class */ (function (_super) {
  74301. __extends(FollowCamera, _super);
  74302. function FollowCamera(name, position, scene, lockedTarget) {
  74303. if (lockedTarget === void 0) { lockedTarget = null; }
  74304. var _this = _super.call(this, name, position, scene) || this;
  74305. _this.radius = 12;
  74306. _this.rotationOffset = 0;
  74307. _this.heightOffset = 4;
  74308. _this.cameraAcceleration = 0.05;
  74309. _this.maxCameraSpeed = 20;
  74310. _this.lockedTarget = lockedTarget;
  74311. return _this;
  74312. }
  74313. FollowCamera.prototype.getRadians = function (degrees) {
  74314. return degrees * Math.PI / 180;
  74315. };
  74316. FollowCamera.prototype.follow = function (cameraTarget) {
  74317. if (!cameraTarget)
  74318. return;
  74319. var yRotation;
  74320. if (cameraTarget.rotationQuaternion) {
  74321. var rotMatrix = new BABYLON.Matrix();
  74322. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  74323. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  74324. }
  74325. else {
  74326. yRotation = cameraTarget.rotation.y;
  74327. }
  74328. var radians = this.getRadians(this.rotationOffset) + yRotation;
  74329. var targetPosition = cameraTarget.getAbsolutePosition();
  74330. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  74331. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  74332. var dx = targetX - this.position.x;
  74333. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  74334. var dz = (targetZ) - this.position.z;
  74335. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  74336. var vy = dy * this.cameraAcceleration;
  74337. var vz = dz * this.cameraAcceleration * 2;
  74338. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  74339. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74340. }
  74341. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  74342. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74343. }
  74344. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  74345. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  74346. }
  74347. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  74348. this.setTarget(targetPosition);
  74349. };
  74350. FollowCamera.prototype._checkInputs = function () {
  74351. _super.prototype._checkInputs.call(this);
  74352. if (this.lockedTarget) {
  74353. this.follow(this.lockedTarget);
  74354. }
  74355. };
  74356. FollowCamera.prototype.getClassName = function () {
  74357. return "FollowCamera";
  74358. };
  74359. __decorate([
  74360. BABYLON.serialize()
  74361. ], FollowCamera.prototype, "radius", void 0);
  74362. __decorate([
  74363. BABYLON.serialize()
  74364. ], FollowCamera.prototype, "rotationOffset", void 0);
  74365. __decorate([
  74366. BABYLON.serialize()
  74367. ], FollowCamera.prototype, "heightOffset", void 0);
  74368. __decorate([
  74369. BABYLON.serialize()
  74370. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  74371. __decorate([
  74372. BABYLON.serialize()
  74373. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  74374. __decorate([
  74375. BABYLON.serializeAsMeshReference("lockedTargetId")
  74376. ], FollowCamera.prototype, "lockedTarget", void 0);
  74377. return FollowCamera;
  74378. }(BABYLON.TargetCamera));
  74379. BABYLON.FollowCamera = FollowCamera;
  74380. var ArcFollowCamera = /** @class */ (function (_super) {
  74381. __extends(ArcFollowCamera, _super);
  74382. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  74383. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  74384. _this.alpha = alpha;
  74385. _this.beta = beta;
  74386. _this.radius = radius;
  74387. _this.target = target;
  74388. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  74389. _this.follow();
  74390. return _this;
  74391. }
  74392. ArcFollowCamera.prototype.follow = function () {
  74393. if (!this.target) {
  74394. return;
  74395. }
  74396. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  74397. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  74398. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  74399. var targetPosition = this.target.getAbsolutePosition();
  74400. this.position = targetPosition.add(this._cartesianCoordinates);
  74401. this.setTarget(targetPosition);
  74402. };
  74403. ArcFollowCamera.prototype._checkInputs = function () {
  74404. _super.prototype._checkInputs.call(this);
  74405. this.follow();
  74406. };
  74407. ArcFollowCamera.prototype.getClassName = function () {
  74408. return "ArcFollowCamera";
  74409. };
  74410. return ArcFollowCamera;
  74411. }(BABYLON.TargetCamera));
  74412. BABYLON.ArcFollowCamera = ArcFollowCamera;
  74413. })(BABYLON || (BABYLON = {}));
  74414. //# sourceMappingURL=babylon.followCamera.js.map
  74415. var BABYLON;
  74416. (function (BABYLON) {
  74417. // We're mainly based on the logic defined into the FreeCamera code
  74418. var UniversalCamera = /** @class */ (function (_super) {
  74419. __extends(UniversalCamera, _super);
  74420. //-- end properties for backward compatibility for inputs
  74421. function UniversalCamera(name, position, scene) {
  74422. var _this = _super.call(this, name, position, scene) || this;
  74423. _this.inputs.addGamepad();
  74424. return _this;
  74425. }
  74426. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  74427. //-- Begin properties for backward compatibility for inputs
  74428. get: function () {
  74429. var gamepad = this.inputs.attached["gamepad"];
  74430. if (gamepad)
  74431. return gamepad.gamepadAngularSensibility;
  74432. return 0;
  74433. },
  74434. set: function (value) {
  74435. var gamepad = this.inputs.attached["gamepad"];
  74436. if (gamepad)
  74437. gamepad.gamepadAngularSensibility = value;
  74438. },
  74439. enumerable: true,
  74440. configurable: true
  74441. });
  74442. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  74443. get: function () {
  74444. var gamepad = this.inputs.attached["gamepad"];
  74445. if (gamepad)
  74446. return gamepad.gamepadMoveSensibility;
  74447. return 0;
  74448. },
  74449. set: function (value) {
  74450. var gamepad = this.inputs.attached["gamepad"];
  74451. if (gamepad)
  74452. gamepad.gamepadMoveSensibility = value;
  74453. },
  74454. enumerable: true,
  74455. configurable: true
  74456. });
  74457. UniversalCamera.prototype.getClassName = function () {
  74458. return "UniversalCamera";
  74459. };
  74460. return UniversalCamera;
  74461. }(BABYLON.TouchCamera));
  74462. BABYLON.UniversalCamera = UniversalCamera;
  74463. })(BABYLON || (BABYLON = {}));
  74464. //# sourceMappingURL=babylon.universalCamera.js.map
  74465. var BABYLON;
  74466. (function (BABYLON) {
  74467. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  74468. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  74469. });
  74470. // We're mainly based on the logic defined into the FreeCamera code
  74471. var GamepadCamera = /** @class */ (function (_super) {
  74472. __extends(GamepadCamera, _super);
  74473. //-- end properties for backward compatibility for inputs
  74474. function GamepadCamera(name, position, scene) {
  74475. return _super.call(this, name, position, scene) || this;
  74476. }
  74477. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  74478. //-- Begin properties for backward compatibility for inputs
  74479. get: function () {
  74480. var gamepad = this.inputs.attached["gamepad"];
  74481. if (gamepad)
  74482. return gamepad.gamepadAngularSensibility;
  74483. return 0;
  74484. },
  74485. set: function (value) {
  74486. var gamepad = this.inputs.attached["gamepad"];
  74487. if (gamepad)
  74488. gamepad.gamepadAngularSensibility = value;
  74489. },
  74490. enumerable: true,
  74491. configurable: true
  74492. });
  74493. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  74494. get: function () {
  74495. var gamepad = this.inputs.attached["gamepad"];
  74496. if (gamepad)
  74497. return gamepad.gamepadMoveSensibility;
  74498. return 0;
  74499. },
  74500. set: function (value) {
  74501. var gamepad = this.inputs.attached["gamepad"];
  74502. if (gamepad)
  74503. gamepad.gamepadMoveSensibility = value;
  74504. },
  74505. enumerable: true,
  74506. configurable: true
  74507. });
  74508. GamepadCamera.prototype.getClassName = function () {
  74509. return "GamepadCamera";
  74510. };
  74511. return GamepadCamera;
  74512. }(BABYLON.UniversalCamera));
  74513. BABYLON.GamepadCamera = GamepadCamera;
  74514. })(BABYLON || (BABYLON = {}));
  74515. //# sourceMappingURL=babylon.gamepadCamera.js.map
  74516. var BABYLON;
  74517. (function (BABYLON) {
  74518. var PostProcessRenderPipelineManager = /** @class */ (function () {
  74519. function PostProcessRenderPipelineManager() {
  74520. this._renderPipelines = {};
  74521. }
  74522. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  74523. this._renderPipelines[renderPipeline._name] = renderPipeline;
  74524. };
  74525. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  74526. if (unique === void 0) { unique = false; }
  74527. var renderPipeline = this._renderPipelines[renderPipelineName];
  74528. if (!renderPipeline) {
  74529. return;
  74530. }
  74531. renderPipeline._attachCameras(cameras, unique);
  74532. };
  74533. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  74534. var renderPipeline = this._renderPipelines[renderPipelineName];
  74535. if (!renderPipeline) {
  74536. return;
  74537. }
  74538. renderPipeline._detachCameras(cameras);
  74539. };
  74540. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74541. var renderPipeline = this._renderPipelines[renderPipelineName];
  74542. if (!renderPipeline) {
  74543. return;
  74544. }
  74545. renderPipeline._enableEffect(renderEffectName, cameras);
  74546. };
  74547. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  74548. var renderPipeline = this._renderPipelines[renderPipelineName];
  74549. if (!renderPipeline) {
  74550. return;
  74551. }
  74552. renderPipeline._disableEffect(renderEffectName, cameras);
  74553. };
  74554. PostProcessRenderPipelineManager.prototype.update = function () {
  74555. for (var renderPipelineName in this._renderPipelines) {
  74556. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74557. var pipeline = this._renderPipelines[renderPipelineName];
  74558. if (!pipeline.isSupported) {
  74559. pipeline.dispose();
  74560. delete this._renderPipelines[renderPipelineName];
  74561. }
  74562. else {
  74563. pipeline._update();
  74564. }
  74565. }
  74566. }
  74567. };
  74568. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  74569. for (var renderPipelineName in this._renderPipelines) {
  74570. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74571. var pipeline = this._renderPipelines[renderPipelineName];
  74572. pipeline._rebuild();
  74573. }
  74574. }
  74575. };
  74576. PostProcessRenderPipelineManager.prototype.dispose = function () {
  74577. for (var renderPipelineName in this._renderPipelines) {
  74578. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  74579. var pipeline = this._renderPipelines[renderPipelineName];
  74580. pipeline.dispose();
  74581. }
  74582. }
  74583. };
  74584. return PostProcessRenderPipelineManager;
  74585. }());
  74586. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  74587. })(BABYLON || (BABYLON = {}));
  74588. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  74589. var BABYLON;
  74590. (function (BABYLON) {
  74591. /**
  74592. * This represents a set of one or more post processes in Babylon.
  74593. * A post process can be used to apply a shader to a texture after it is rendered.
  74594. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  74595. */
  74596. var PostProcessRenderEffect = /** @class */ (function () {
  74597. /**
  74598. * Instantiates a post process render effect.
  74599. * A post process can be used to apply a shader to a texture after it is rendered.
  74600. * @param engine The engine the effect is tied to
  74601. * @param name The name of the effect
  74602. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  74603. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  74604. */
  74605. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  74606. this._name = name;
  74607. this._singleInstance = singleInstance || true;
  74608. this._getPostProcesses = getPostProcesses;
  74609. this._cameras = {};
  74610. this._indicesForCamera = {};
  74611. this._postProcesses = {};
  74612. }
  74613. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  74614. /**
  74615. * Checks if all the post processes in the effect are supported.
  74616. */
  74617. get: function () {
  74618. for (var index in this._postProcesses) {
  74619. if (this._postProcesses.hasOwnProperty(index)) {
  74620. var pps = this._postProcesses[index];
  74621. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  74622. if (!pps[ppIndex].isSupported) {
  74623. return false;
  74624. }
  74625. }
  74626. }
  74627. }
  74628. return true;
  74629. },
  74630. enumerable: true,
  74631. configurable: true
  74632. });
  74633. /**
  74634. * Updates the current state of the effect
  74635. */
  74636. PostProcessRenderEffect.prototype._update = function () {
  74637. };
  74638. /**
  74639. * Attaches the effect on cameras
  74640. * @param cameras The camera to attach to.
  74641. */
  74642. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  74643. var _this = this;
  74644. var cameraKey;
  74645. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74646. if (!cams) {
  74647. return;
  74648. }
  74649. for (var i = 0; i < cams.length; i++) {
  74650. var camera = cams[i];
  74651. var cameraName = camera.name;
  74652. if (this._singleInstance) {
  74653. cameraKey = 0;
  74654. }
  74655. else {
  74656. cameraKey = cameraName;
  74657. }
  74658. if (!this._postProcesses[cameraKey]) {
  74659. var postProcess = this._getPostProcesses();
  74660. if (postProcess) {
  74661. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  74662. }
  74663. }
  74664. if (!this._indicesForCamera[cameraName]) {
  74665. this._indicesForCamera[cameraName] = [];
  74666. }
  74667. this._postProcesses[cameraKey].forEach(function (postProcess) {
  74668. var index = camera.attachPostProcess(postProcess);
  74669. _this._indicesForCamera[cameraName].push(index);
  74670. });
  74671. if (!this._cameras[cameraName]) {
  74672. this._cameras[cameraName] = camera;
  74673. }
  74674. }
  74675. };
  74676. /**
  74677. * Detatches the effect on cameras
  74678. * @param cameras The camera to detatch from.
  74679. */
  74680. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  74681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74682. if (!cams) {
  74683. return;
  74684. }
  74685. for (var i = 0; i < cams.length; i++) {
  74686. var camera = cams[i];
  74687. var cameraName = camera.name;
  74688. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74689. camera.detachPostProcess(postProcess);
  74690. });
  74691. if (this._cameras[cameraName]) {
  74692. //this._indicesForCamera.splice(index, 1);
  74693. this._cameras[cameraName] = null;
  74694. }
  74695. }
  74696. };
  74697. /**
  74698. * Enables the effect on given cameras
  74699. * @param cameras The camera to enable.
  74700. */
  74701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  74702. var _this = this;
  74703. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74704. if (!cams) {
  74705. return;
  74706. }
  74707. for (var i = 0; i < cams.length; i++) {
  74708. var camera = cams[i];
  74709. var cameraName = camera.name;
  74710. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  74711. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  74712. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74713. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  74714. });
  74715. }
  74716. }
  74717. }
  74718. };
  74719. /**
  74720. * Disables the effect on the given cameras
  74721. * @param cameras The camera to disable.
  74722. */
  74723. PostProcessRenderEffect.prototype._disable = function (cameras) {
  74724. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74725. if (!cams) {
  74726. return;
  74727. }
  74728. for (var i = 0; i < cams.length; i++) {
  74729. var camera = cams[i];
  74730. var cameraName = camera.name;
  74731. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  74732. camera.detachPostProcess(postProcess);
  74733. });
  74734. }
  74735. };
  74736. /**
  74737. * Gets a list of the post processes contained in the effect.
  74738. * @param camera The camera to get the post processes on.
  74739. * @returns The list of the post processes in the effect.
  74740. */
  74741. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  74742. if (this._singleInstance) {
  74743. return this._postProcesses[0];
  74744. }
  74745. else {
  74746. if (!camera) {
  74747. return null;
  74748. }
  74749. return this._postProcesses[camera.name];
  74750. }
  74751. };
  74752. return PostProcessRenderEffect;
  74753. }());
  74754. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  74755. })(BABYLON || (BABYLON = {}));
  74756. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  74757. var BABYLON;
  74758. (function (BABYLON) {
  74759. var PostProcessRenderPipeline = /** @class */ (function () {
  74760. function PostProcessRenderPipeline(engine, name) {
  74761. this.engine = engine;
  74762. this._name = name;
  74763. this._renderEffects = {};
  74764. this._renderEffectsForIsolatedPass = new Array();
  74765. this._cameras = [];
  74766. }
  74767. PostProcessRenderPipeline.prototype.getClassName = function () {
  74768. return "PostProcessRenderPipeline";
  74769. };
  74770. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  74771. get: function () {
  74772. for (var renderEffectName in this._renderEffects) {
  74773. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74774. if (!this._renderEffects[renderEffectName].isSupported) {
  74775. return false;
  74776. }
  74777. }
  74778. }
  74779. return true;
  74780. },
  74781. enumerable: true,
  74782. configurable: true
  74783. });
  74784. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  74785. this._renderEffects[renderEffect._name] = renderEffect;
  74786. };
  74787. // private
  74788. PostProcessRenderPipeline.prototype._rebuild = function () {
  74789. };
  74790. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  74791. var renderEffects = this._renderEffects[renderEffectName];
  74792. if (!renderEffects) {
  74793. return;
  74794. }
  74795. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74796. };
  74797. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  74798. var renderEffects = this._renderEffects[renderEffectName];
  74799. if (!renderEffects) {
  74800. return;
  74801. }
  74802. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  74803. };
  74804. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  74805. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74806. if (!cams) {
  74807. return;
  74808. }
  74809. var indicesToDelete = [];
  74810. var i;
  74811. for (i = 0; i < cams.length; i++) {
  74812. var camera = cams[i];
  74813. var cameraName = camera.name;
  74814. if (this._cameras.indexOf(camera) === -1) {
  74815. this._cameras[cameraName] = camera;
  74816. }
  74817. else if (unique) {
  74818. indicesToDelete.push(i);
  74819. }
  74820. }
  74821. for (i = 0; i < indicesToDelete.length; i++) {
  74822. cameras.splice(indicesToDelete[i], 1);
  74823. }
  74824. for (var renderEffectName in this._renderEffects) {
  74825. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74826. this._renderEffects[renderEffectName]._attachCameras(cams);
  74827. }
  74828. }
  74829. };
  74830. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  74831. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  74832. if (!cams) {
  74833. return;
  74834. }
  74835. for (var renderEffectName in this._renderEffects) {
  74836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74837. this._renderEffects[renderEffectName]._detachCameras(cams);
  74838. }
  74839. }
  74840. for (var i = 0; i < cams.length; i++) {
  74841. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  74842. }
  74843. };
  74844. PostProcessRenderPipeline.prototype._update = function () {
  74845. for (var renderEffectName in this._renderEffects) {
  74846. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  74847. this._renderEffects[renderEffectName]._update();
  74848. }
  74849. }
  74850. for (var i = 0; i < this._cameras.length; i++) {
  74851. var cameraName = this._cameras[i].name;
  74852. if (this._renderEffectsForIsolatedPass[cameraName]) {
  74853. this._renderEffectsForIsolatedPass[cameraName]._update();
  74854. }
  74855. }
  74856. };
  74857. PostProcessRenderPipeline.prototype._reset = function () {
  74858. this._renderEffects = {};
  74859. this._renderEffectsForIsolatedPass = new Array();
  74860. };
  74861. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  74862. // 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)
  74863. var effectKeys = Object.keys(this._renderEffects);
  74864. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  74865. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  74866. if (postProcesses) {
  74867. postProcesses[0].samples = sampleCount;
  74868. return true;
  74869. }
  74870. }
  74871. return false;
  74872. };
  74873. PostProcessRenderPipeline.prototype.dispose = function () {
  74874. // Must be implemented by children
  74875. };
  74876. __decorate([
  74877. BABYLON.serialize()
  74878. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  74879. return PostProcessRenderPipeline;
  74880. }());
  74881. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  74882. })(BABYLON || (BABYLON = {}));
  74883. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  74884. var BABYLON;
  74885. (function (BABYLON) {
  74886. /**
  74887. * This represents a depth renderer in Babylon.
  74888. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  74889. */
  74890. var DepthRenderer = /** @class */ (function () {
  74891. /**
  74892. * Instantiates a depth renderer
  74893. * @param scene The scene the renderer belongs to
  74894. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  74895. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  74896. */
  74897. function DepthRenderer(scene, type, camera) {
  74898. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  74899. if (camera === void 0) { camera = null; }
  74900. var _this = this;
  74901. this._scene = scene;
  74902. this._camera = camera;
  74903. var engine = scene.getEngine();
  74904. // Render target
  74905. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  74906. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74907. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  74908. this._depthMap.refreshRate = 1;
  74909. this._depthMap.renderParticles = false;
  74910. this._depthMap.renderList = null;
  74911. // Camera to get depth map from to support multiple concurrent cameras
  74912. this._depthMap.activeCamera = this._camera;
  74913. this._depthMap.ignoreCameraViewport = true;
  74914. this._depthMap.useCameraPostProcesses = false;
  74915. // set default depth value to 1.0 (far away)
  74916. this._depthMap.onClearObservable.add(function (engine) {
  74917. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  74918. });
  74919. // Custom render function
  74920. var renderSubMesh = function (subMesh) {
  74921. var mesh = subMesh.getRenderingMesh();
  74922. var scene = _this._scene;
  74923. var engine = scene.getEngine();
  74924. var material = subMesh.getMaterial();
  74925. if (!material) {
  74926. return;
  74927. }
  74928. // Culling and reverse (right handed system)
  74929. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  74930. // Managing instances
  74931. var batch = mesh._getInstancesRenderList(subMesh._id);
  74932. if (batch.mustReturn) {
  74933. return;
  74934. }
  74935. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  74936. var camera = _this._camera || scene.activeCamera;
  74937. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  74938. engine.enableEffect(_this._effect);
  74939. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  74940. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  74941. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  74942. // Alpha test
  74943. if (material && material.needAlphaTesting()) {
  74944. var alphaTexture = material.getAlphaTestTexture();
  74945. if (alphaTexture) {
  74946. _this._effect.setTexture("diffuseSampler", alphaTexture);
  74947. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  74948. }
  74949. }
  74950. // Bones
  74951. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  74952. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  74953. }
  74954. // Draw
  74955. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  74956. }
  74957. };
  74958. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  74959. var index;
  74960. if (depthOnlySubMeshes.length) {
  74961. engine.setColorWrite(false);
  74962. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  74963. renderSubMesh(depthOnlySubMeshes.data[index]);
  74964. }
  74965. engine.setColorWrite(true);
  74966. }
  74967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  74968. renderSubMesh(opaqueSubMeshes.data[index]);
  74969. }
  74970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  74971. renderSubMesh(alphaTestSubMeshes.data[index]);
  74972. }
  74973. };
  74974. }
  74975. /**
  74976. * Creates the depth rendering effect and checks if the effect is ready.
  74977. * @param subMesh The submesh to be used to render the depth map of
  74978. * @param useInstances If multiple world instances should be used
  74979. * @returns if the depth renderer is ready to render the depth map
  74980. */
  74981. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  74982. var material = subMesh.getMaterial();
  74983. if (material.disableDepthWrite) {
  74984. return false;
  74985. }
  74986. var defines = [];
  74987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  74988. var mesh = subMesh.getMesh();
  74989. // Alpha test
  74990. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  74991. defines.push("#define ALPHATEST");
  74992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  74993. attribs.push(BABYLON.VertexBuffer.UVKind);
  74994. defines.push("#define UV1");
  74995. }
  74996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  74997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  74998. defines.push("#define UV2");
  74999. }
  75000. }
  75001. // Bones
  75002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75005. if (mesh.numBoneInfluencers > 4) {
  75006. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75007. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75008. }
  75009. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75010. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75011. }
  75012. else {
  75013. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75014. }
  75015. // Instances
  75016. if (useInstances) {
  75017. defines.push("#define INSTANCES");
  75018. attribs.push("world0");
  75019. attribs.push("world1");
  75020. attribs.push("world2");
  75021. attribs.push("world3");
  75022. }
  75023. // Get correct effect
  75024. var join = defines.join("\n");
  75025. if (this._cachedDefines !== join) {
  75026. this._cachedDefines = join;
  75027. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  75028. }
  75029. return this._effect.isReady();
  75030. };
  75031. /**
  75032. * Gets the texture which the depth map will be written to.
  75033. * @returns The depth map texture
  75034. */
  75035. DepthRenderer.prototype.getDepthMap = function () {
  75036. return this._depthMap;
  75037. };
  75038. /**
  75039. * Disposes of the depth renderer.
  75040. */
  75041. DepthRenderer.prototype.dispose = function () {
  75042. this._depthMap.dispose();
  75043. };
  75044. return DepthRenderer;
  75045. }());
  75046. BABYLON.DepthRenderer = DepthRenderer;
  75047. })(BABYLON || (BABYLON = {}));
  75048. //# sourceMappingURL=babylon.depthRenderer.js.map
  75049. var BABYLON;
  75050. (function (BABYLON) {
  75051. var SSAORenderingPipeline = /** @class */ (function (_super) {
  75052. __extends(SSAORenderingPipeline, _super);
  75053. /**
  75054. * @constructor
  75055. * @param {string} name - The rendering pipeline name
  75056. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75057. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  75058. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75059. */
  75060. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  75061. var _this = _super.call(this, scene.getEngine(), name) || this;
  75062. // Members
  75063. /**
  75064. * The PassPostProcess id in the pipeline that contains the original scene color
  75065. */
  75066. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75067. /**
  75068. * The SSAO PostProcess id in the pipeline
  75069. */
  75070. _this.SSAORenderEffect = "SSAORenderEffect";
  75071. /**
  75072. * The horizontal blur PostProcess id in the pipeline
  75073. */
  75074. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75075. /**
  75076. * The vertical blur PostProcess id in the pipeline
  75077. */
  75078. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75079. /**
  75080. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75081. */
  75082. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75083. /**
  75084. * The output strength of the SSAO post-process. Default value is 1.0.
  75085. */
  75086. _this.totalStrength = 1.0;
  75087. /**
  75088. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  75089. */
  75090. _this.radius = 0.0001;
  75091. /**
  75092. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  75093. * Must not be equal to fallOff and superior to fallOff.
  75094. * Default value is 0.975
  75095. */
  75096. _this.area = 0.0075;
  75097. /**
  75098. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  75099. * Must not be equal to area and inferior to area.
  75100. * Default value is 0.0
  75101. */
  75102. _this.fallOff = 0.000001;
  75103. /**
  75104. * The base color of the SSAO post-process
  75105. * The final result is "base + ssao" between [0, 1]
  75106. */
  75107. _this.base = 0.5;
  75108. _this._firstUpdate = true;
  75109. _this._scene = scene;
  75110. // Set up assets
  75111. _this._createRandomTexture();
  75112. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75113. var ssaoRatio = ratio.ssaoRatio || ratio;
  75114. var combineRatio = ratio.combineRatio || ratio;
  75115. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75116. _this._createSSAOPostProcess(ssaoRatio);
  75117. _this._createBlurPostProcess(ssaoRatio);
  75118. _this._createSSAOCombinePostProcess(combineRatio);
  75119. // Set up pipeline
  75120. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75121. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75122. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75125. // Finish
  75126. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75127. if (cameras)
  75128. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75129. return _this;
  75130. }
  75131. // Public Methods
  75132. /**
  75133. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75134. */
  75135. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75136. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75137. for (var i = 0; i < this._scene.cameras.length; i++) {
  75138. var camera = this._scene.cameras[i];
  75139. this._originalColorPostProcess.dispose(camera);
  75140. this._ssaoPostProcess.dispose(camera);
  75141. this._blurHPostProcess.dispose(camera);
  75142. this._blurVPostProcess.dispose(camera);
  75143. this._ssaoCombinePostProcess.dispose(camera);
  75144. }
  75145. this._randomTexture.dispose();
  75146. if (disableDepthRender)
  75147. this._scene.disableDepthRenderer();
  75148. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75149. _super.prototype.dispose.call(this);
  75150. };
  75151. // Private Methods
  75152. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  75153. var _this = this;
  75154. var size = 16;
  75155. 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);
  75156. 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);
  75157. this._blurHPostProcess.onActivateObservable.add(function () {
  75158. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  75159. _this._blurHPostProcess.kernel = size * dw;
  75160. });
  75161. this._blurVPostProcess.onActivateObservable.add(function () {
  75162. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  75163. _this._blurVPostProcess.kernel = size * dw;
  75164. });
  75165. };
  75166. SSAORenderingPipeline.prototype._rebuild = function () {
  75167. this._firstUpdate = true;
  75168. _super.prototype._rebuild.call(this);
  75169. };
  75170. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75171. var _this = this;
  75172. var numSamples = 16;
  75173. var sampleSphere = [
  75174. 0.5381, 0.1856, -0.4319,
  75175. 0.1379, 0.2486, 0.4430,
  75176. 0.3371, 0.5679, -0.0057,
  75177. -0.6999, -0.0451, -0.0019,
  75178. 0.0689, -0.1598, -0.8547,
  75179. 0.0560, 0.0069, -0.1843,
  75180. -0.0146, 0.1402, 0.0762,
  75181. 0.0100, -0.1924, -0.0344,
  75182. -0.3577, -0.5301, -0.4358,
  75183. -0.3169, 0.1063, 0.0158,
  75184. 0.0103, -0.5869, 0.0046,
  75185. -0.0897, -0.4940, 0.3287,
  75186. 0.7119, -0.0154, -0.0918,
  75187. -0.0533, 0.0596, -0.5411,
  75188. 0.0352, -0.0631, 0.5460,
  75189. -0.4776, 0.2847, -0.0271
  75190. ];
  75191. var samplesFactor = 1.0 / numSamples;
  75192. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  75193. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75194. "area", "fallOff", "base", "range", "viewport"
  75195. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75196. this._ssaoPostProcess.onApply = function (effect) {
  75197. if (_this._firstUpdate) {
  75198. effect.setArray3("sampleSphere", sampleSphere);
  75199. effect.setFloat("samplesFactor", samplesFactor);
  75200. effect.setFloat("randTextureTiles", 4.0);
  75201. }
  75202. effect.setFloat("totalStrength", _this.totalStrength);
  75203. effect.setFloat("radius", _this.radius);
  75204. effect.setFloat("area", _this.area);
  75205. effect.setFloat("fallOff", _this.fallOff);
  75206. effect.setFloat("base", _this.base);
  75207. effect.setTexture("textureSampler", _this._depthTexture);
  75208. effect.setTexture("randomSampler", _this._randomTexture);
  75209. };
  75210. };
  75211. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75212. var _this = this;
  75213. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75214. this._ssaoCombinePostProcess.onApply = function (effect) {
  75215. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  75216. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75217. };
  75218. };
  75219. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  75220. var size = 512;
  75221. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75222. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75223. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75224. var context = this._randomTexture.getContext();
  75225. var rand = function (min, max) {
  75226. return Math.random() * (max - min) + min;
  75227. };
  75228. var randVector = BABYLON.Vector3.Zero();
  75229. for (var x = 0; x < size; x++) {
  75230. for (var y = 0; y < size; y++) {
  75231. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  75232. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  75233. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  75234. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75235. context.fillRect(x, y, 1, 1);
  75236. }
  75237. }
  75238. this._randomTexture.update(false);
  75239. };
  75240. __decorate([
  75241. BABYLON.serialize()
  75242. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  75243. __decorate([
  75244. BABYLON.serialize()
  75245. ], SSAORenderingPipeline.prototype, "radius", void 0);
  75246. __decorate([
  75247. BABYLON.serialize()
  75248. ], SSAORenderingPipeline.prototype, "area", void 0);
  75249. __decorate([
  75250. BABYLON.serialize()
  75251. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  75252. __decorate([
  75253. BABYLON.serialize()
  75254. ], SSAORenderingPipeline.prototype, "base", void 0);
  75255. return SSAORenderingPipeline;
  75256. }(BABYLON.PostProcessRenderPipeline));
  75257. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  75258. })(BABYLON || (BABYLON = {}));
  75259. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  75260. var BABYLON;
  75261. (function (BABYLON) {
  75262. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  75263. __extends(SSAO2RenderingPipeline, _super);
  75264. /**
  75265. * @constructor
  75266. * @param {string} name - The rendering pipeline name
  75267. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75268. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  75269. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75270. */
  75271. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  75272. var _this = _super.call(this, scene.getEngine(), name) || this;
  75273. // Members
  75274. /**
  75275. * The PassPostProcess id in the pipeline that contains the original scene color
  75276. */
  75277. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  75278. /**
  75279. * The SSAO PostProcess id in the pipeline
  75280. */
  75281. _this.SSAORenderEffect = "SSAORenderEffect";
  75282. /**
  75283. * The horizontal blur PostProcess id in the pipeline
  75284. */
  75285. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  75286. /**
  75287. * The vertical blur PostProcess id in the pipeline
  75288. */
  75289. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  75290. /**
  75291. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  75292. */
  75293. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  75294. /**
  75295. * The output strength of the SSAO post-process. Default value is 1.0.
  75296. */
  75297. _this.totalStrength = 1.0;
  75298. /**
  75299. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  75300. */
  75301. _this.maxZ = 100.0;
  75302. /**
  75303. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  75304. */
  75305. _this.minZAspect = 0.2;
  75306. /**
  75307. * Number of samples used for the SSAO calculations. Default value is 8
  75308. */
  75309. _this._samples = 8;
  75310. /**
  75311. * Are we using bilateral blur ?
  75312. */
  75313. _this._expensiveBlur = true;
  75314. /**
  75315. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  75316. */
  75317. _this.radius = 2.0;
  75318. /**
  75319. * The base color of the SSAO post-process
  75320. * The final result is "base + ssao" between [0, 1]
  75321. */
  75322. _this.base = 0.1;
  75323. _this._firstUpdate = true;
  75324. _this._scene = scene;
  75325. _this._ratio = ratio;
  75326. if (!_this.isSupported) {
  75327. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  75328. return _this;
  75329. }
  75330. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  75331. var blurRatio = _this._ratio.blurRatio || ratio;
  75332. // Set up assets
  75333. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  75334. _this._createRandomTexture();
  75335. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  75336. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  75337. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  75338. _this._createSSAOPostProcess(1.0);
  75339. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  75340. _this._createSSAOCombinePostProcess(blurRatio);
  75341. // Set up pipeline
  75342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  75343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  75344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  75345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  75346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  75347. // Finish
  75348. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75349. if (cameras)
  75350. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75351. return _this;
  75352. }
  75353. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  75354. get: function () {
  75355. return this._samples;
  75356. },
  75357. set: function (n) {
  75358. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  75359. this._samples = n;
  75360. this._sampleSphere = this._generateHemisphere();
  75361. this._firstUpdate = true;
  75362. },
  75363. enumerable: true,
  75364. configurable: true
  75365. });
  75366. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  75367. get: function () {
  75368. return this._expensiveBlur;
  75369. },
  75370. set: function (b) {
  75371. 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"]);
  75372. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  75373. this._expensiveBlur = b;
  75374. this._firstUpdate = true;
  75375. },
  75376. enumerable: true,
  75377. configurable: true
  75378. });
  75379. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  75380. /**
  75381. * Support test.
  75382. */
  75383. get: function () {
  75384. var engine = BABYLON.Engine.LastCreatedEngine;
  75385. if (!engine) {
  75386. return false;
  75387. }
  75388. return engine.getCaps().drawBuffersExtension;
  75389. },
  75390. enumerable: true,
  75391. configurable: true
  75392. });
  75393. // Public Methods
  75394. /**
  75395. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  75396. */
  75397. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  75398. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  75399. for (var i = 0; i < this._scene.cameras.length; i++) {
  75400. var camera = this._scene.cameras[i];
  75401. this._originalColorPostProcess.dispose(camera);
  75402. this._ssaoPostProcess.dispose(camera);
  75403. this._blurHPostProcess.dispose(camera);
  75404. this._blurVPostProcess.dispose(camera);
  75405. this._ssaoCombinePostProcess.dispose(camera);
  75406. }
  75407. this._randomTexture.dispose();
  75408. if (disableGeometryBufferRenderer)
  75409. this._scene.disableGeometryBufferRenderer();
  75410. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75411. _super.prototype.dispose.call(this);
  75412. };
  75413. // Private Methods
  75414. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  75415. var _this = this;
  75416. this._samplerOffsets = [];
  75417. var expensive = this.expensiveBlur;
  75418. for (var i = -8; i < 8; i++) {
  75419. this._samplerOffsets.push(i * 2 + 0.5);
  75420. }
  75421. 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");
  75422. this._blurHPostProcess.onApply = function (effect) {
  75423. if (!_this._scene.activeCamera) {
  75424. return;
  75425. }
  75426. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  75427. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75428. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75429. effect.setFloat("radius", _this.radius);
  75430. effect.setTexture("depthSampler", _this._depthTexture);
  75431. if (_this._firstUpdate) {
  75432. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75433. }
  75434. };
  75435. 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");
  75436. this._blurVPostProcess.onApply = function (effect) {
  75437. if (!_this._scene.activeCamera) {
  75438. return;
  75439. }
  75440. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  75441. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75442. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75443. effect.setFloat("radius", _this.radius);
  75444. effect.setTexture("depthSampler", _this._depthTexture);
  75445. if (_this._firstUpdate) {
  75446. effect.setArray("samplerOffsets", _this._samplerOffsets);
  75447. _this._firstUpdate = false;
  75448. }
  75449. };
  75450. };
  75451. SSAO2RenderingPipeline.prototype._rebuild = function () {
  75452. this._firstUpdate = true;
  75453. _super.prototype._rebuild.call(this);
  75454. };
  75455. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  75456. var numSamples = this.samples;
  75457. var result = [];
  75458. var vector, scale;
  75459. var rand = function (min, max) {
  75460. return Math.random() * (max - min) + min;
  75461. };
  75462. var i = 0;
  75463. while (i < numSamples) {
  75464. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  75465. vector.normalize();
  75466. scale = i / numSamples;
  75467. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  75468. vector.scaleInPlace(scale);
  75469. result.push(vector.x, vector.y, vector.z);
  75470. i++;
  75471. }
  75472. return result;
  75473. };
  75474. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  75475. var _this = this;
  75476. var numSamples = this.samples;
  75477. this._sampleSphere = this._generateHemisphere();
  75478. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  75479. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  75480. "base", "range", "projection", "near", "far", "texelSize",
  75481. "xViewport", "yViewport", "maxZ", "minZAspect"
  75482. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  75483. this._ssaoPostProcess.onApply = function (effect) {
  75484. if (_this._firstUpdate) {
  75485. effect.setArray3("sampleSphere", _this._sampleSphere);
  75486. effect.setFloat("randTextureTiles", 4.0);
  75487. }
  75488. if (!_this._scene.activeCamera) {
  75489. return;
  75490. }
  75491. effect.setFloat("samplesFactor", 1 / _this.samples);
  75492. effect.setFloat("totalStrength", _this.totalStrength);
  75493. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  75494. effect.setFloat("radius", _this.radius);
  75495. effect.setFloat("maxZ", _this.maxZ);
  75496. effect.setFloat("minZAspect", _this.minZAspect);
  75497. effect.setFloat("base", _this.base);
  75498. effect.setFloat("near", _this._scene.activeCamera.minZ);
  75499. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  75500. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  75501. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  75502. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  75503. effect.setTexture("textureSampler", _this._depthTexture);
  75504. effect.setTexture("normalSampler", _this._normalTexture);
  75505. effect.setTexture("randomSampler", _this._randomTexture);
  75506. };
  75507. };
  75508. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  75509. var _this = this;
  75510. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75511. this._ssaoCombinePostProcess.onApply = function (effect) {
  75512. var viewport = _this._scene.activeCamera.viewport;
  75513. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  75514. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  75515. };
  75516. };
  75517. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  75518. var size = 512;
  75519. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75520. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75521. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75522. var context = this._randomTexture.getContext();
  75523. var rand = function (min, max) {
  75524. return Math.random() * (max - min) + min;
  75525. };
  75526. var randVector = BABYLON.Vector3.Zero();
  75527. for (var x = 0; x < size; x++) {
  75528. for (var y = 0; y < size; y++) {
  75529. randVector.x = rand(0.0, 1.0);
  75530. randVector.y = rand(0.0, 1.0);
  75531. randVector.z = 0.0;
  75532. randVector.normalize();
  75533. randVector.scaleInPlace(255);
  75534. randVector.x = Math.floor(randVector.x);
  75535. randVector.y = Math.floor(randVector.y);
  75536. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  75537. context.fillRect(x, y, 1, 1);
  75538. }
  75539. }
  75540. this._randomTexture.update(false);
  75541. };
  75542. /**
  75543. * Serialize the rendering pipeline (Used when exporting)
  75544. * @returns the serialized object
  75545. */
  75546. SSAO2RenderingPipeline.prototype.serialize = function () {
  75547. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75548. serializationObject.customType = "SSAO2RenderingPipeline";
  75549. return serializationObject;
  75550. };
  75551. /**
  75552. * Parse the serialized pipeline
  75553. * @param source Source pipeline.
  75554. * @param scene The scene to load the pipeline to.
  75555. * @param rootUrl The URL of the serialized pipeline.
  75556. * @returns An instantiated pipeline from the serialized object.
  75557. */
  75558. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  75559. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75560. };
  75561. __decorate([
  75562. BABYLON.serialize()
  75563. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  75564. __decorate([
  75565. BABYLON.serialize()
  75566. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  75567. __decorate([
  75568. BABYLON.serialize()
  75569. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  75570. __decorate([
  75571. BABYLON.serialize("samples")
  75572. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  75573. __decorate([
  75574. BABYLON.serialize()
  75575. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  75576. __decorate([
  75577. BABYLON.serialize("expensiveBlur")
  75578. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  75579. __decorate([
  75580. BABYLON.serialize()
  75581. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  75582. __decorate([
  75583. BABYLON.serialize()
  75584. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  75585. return SSAO2RenderingPipeline;
  75586. }(BABYLON.PostProcessRenderPipeline));
  75587. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  75588. })(BABYLON || (BABYLON = {}));
  75589. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  75590. // BABYLON.JS Chromatic Aberration GLSL Shader
  75591. // Author: Olivier Guyot
  75592. // Separates very slightly R, G and B colors on the edges of the screen
  75593. // Inspired by Francois Tarlier & Martins Upitis
  75594. var BABYLON;
  75595. (function (BABYLON) {
  75596. var LensRenderingPipeline = /** @class */ (function (_super) {
  75597. __extends(LensRenderingPipeline, _super);
  75598. /**
  75599. * @constructor
  75600. *
  75601. * Effect parameters are as follow:
  75602. * {
  75603. * chromatic_aberration: number; // from 0 to x (1 for realism)
  75604. * edge_blur: number; // from 0 to x (1 for realism)
  75605. * distortion: number; // from 0 to x (1 for realism)
  75606. * grain_amount: number; // from 0 to 1
  75607. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  75608. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  75609. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  75610. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  75611. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  75612. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  75613. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  75614. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  75615. * }
  75616. * Note: if an effect parameter is unset, effect is disabled
  75617. *
  75618. * @param {string} name - The rendering pipeline name
  75619. * @param {object} parameters - An object containing all parameters (see above)
  75620. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75621. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  75622. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75623. */
  75624. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  75625. if (ratio === void 0) { ratio = 1.0; }
  75626. var _this = _super.call(this, scene.getEngine(), name) || this;
  75627. // Lens effects can be of the following:
  75628. // - chromatic aberration (slight shift of RGB colors)
  75629. // - blur on the edge of the lens
  75630. // - lens distortion
  75631. // - depth-of-field blur & highlights enhancing
  75632. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  75633. // - grain effect (noise or custom texture)
  75634. // Two additional texture samplers are needed:
  75635. // - depth map (for depth-of-field)
  75636. // - grain texture
  75637. /**
  75638. * The chromatic aberration PostProcess id in the pipeline
  75639. */
  75640. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  75641. /**
  75642. * The highlights enhancing PostProcess id in the pipeline
  75643. */
  75644. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  75645. /**
  75646. * The depth-of-field PostProcess id in the pipeline
  75647. */
  75648. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  75649. _this._scene = scene;
  75650. // Fetch texture samplers
  75651. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  75652. if (parameters.grain_texture) {
  75653. _this._grainTexture = parameters.grain_texture;
  75654. }
  75655. else {
  75656. _this._createGrainTexture();
  75657. }
  75658. // save parameters
  75659. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  75660. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  75661. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  75662. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  75663. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  75664. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  75665. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  75666. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  75667. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  75668. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  75669. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  75670. // Create effects
  75671. _this._createChromaticAberrationPostProcess(ratio);
  75672. _this._createHighlightsPostProcess(ratio);
  75673. _this._createDepthOfFieldPostProcess(ratio / 4);
  75674. // Set up pipeline
  75675. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  75676. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  75677. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  75678. if (_this._highlightsGain === -1) {
  75679. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  75680. }
  75681. // Finish
  75682. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75683. if (cameras) {
  75684. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  75685. }
  75686. return _this;
  75687. }
  75688. // public methods (self explanatory)
  75689. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  75690. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  75691. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  75692. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  75693. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  75694. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  75695. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  75696. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  75697. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  75698. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  75699. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  75700. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  75701. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  75702. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  75703. };
  75704. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  75705. this._highlightsPostProcess.updateEffect();
  75706. };
  75707. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  75708. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  75709. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  75710. this._highlightsGain = amount;
  75711. };
  75712. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  75713. if (this._highlightsGain === -1) {
  75714. this._highlightsGain = 1.0;
  75715. }
  75716. this._highlightsThreshold = amount;
  75717. };
  75718. LensRenderingPipeline.prototype.disableHighlights = function () {
  75719. this._highlightsGain = -1;
  75720. };
  75721. /**
  75722. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  75723. */
  75724. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  75725. if (disableDepthRender === void 0) { disableDepthRender = false; }
  75726. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  75727. this._chromaticAberrationPostProcess = null;
  75728. this._highlightsPostProcess = null;
  75729. this._depthOfFieldPostProcess = null;
  75730. this._grainTexture.dispose();
  75731. if (disableDepthRender)
  75732. this._scene.disableDepthRenderer();
  75733. };
  75734. // colors shifting and distortion
  75735. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  75736. var _this = this;
  75737. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  75738. [], // samplers
  75739. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75740. this._chromaticAberrationPostProcess.onApply = function (effect) {
  75741. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  75742. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75743. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75744. effect.setFloat('radialIntensity', 1);
  75745. effect.setFloat2('direction', 17, 17);
  75746. effect.setFloat2('centerPosition', 0.5, 0.5);
  75747. };
  75748. };
  75749. // highlights enhancing
  75750. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  75751. var _this = this;
  75752. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  75753. [], // samplers
  75754. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  75755. this._highlightsPostProcess.onApply = function (effect) {
  75756. effect.setFloat('gain', _this._highlightsGain);
  75757. effect.setFloat('threshold', _this._highlightsThreshold);
  75758. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  75759. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75760. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75761. };
  75762. };
  75763. // colors shifting and distortion
  75764. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  75765. var _this = this;
  75766. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  75767. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  75768. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  75769. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  75770. this._depthOfFieldPostProcess.onApply = function (effect) {
  75771. effect.setTexture("depthSampler", _this._depthTexture);
  75772. effect.setTexture("grainSampler", _this._grainTexture);
  75773. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  75774. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  75775. effect.setFloat('grain_amount', _this._grainAmount);
  75776. effect.setBool('blur_noise', _this._blurNoise);
  75777. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  75778. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  75779. effect.setFloat('distortion', _this._distortion);
  75780. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  75781. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  75782. effect.setFloat('aperture', _this._dofAperture);
  75783. effect.setFloat('darken', _this._dofDarken);
  75784. effect.setFloat('edge_blur', _this._edgeBlur);
  75785. effect.setBool('highlights', (_this._highlightsGain !== -1));
  75786. if (_this._scene.activeCamera) {
  75787. effect.setFloat('near', _this._scene.activeCamera.minZ);
  75788. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  75789. }
  75790. };
  75791. };
  75792. // creates a black and white random noise texture, 512x512
  75793. LensRenderingPipeline.prototype._createGrainTexture = function () {
  75794. var size = 512;
  75795. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75796. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  75797. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  75798. var context = this._grainTexture.getContext();
  75799. var rand = function (min, max) {
  75800. return Math.random() * (max - min) + min;
  75801. };
  75802. var value;
  75803. for (var x = 0; x < size; x++) {
  75804. for (var y = 0; y < size; y++) {
  75805. value = Math.floor(rand(0.42, 0.58) * 255);
  75806. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  75807. context.fillRect(x, y, 1, 1);
  75808. }
  75809. }
  75810. this._grainTexture.update(false);
  75811. };
  75812. return LensRenderingPipeline;
  75813. }(BABYLON.PostProcessRenderPipeline));
  75814. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  75815. })(BABYLON || (BABYLON = {}));
  75816. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  75817. var BABYLON;
  75818. (function (BABYLON) {
  75819. var StandardRenderingPipeline = /** @class */ (function (_super) {
  75820. __extends(StandardRenderingPipeline, _super);
  75821. /**
  75822. * @constructor
  75823. * @param {string} name - The rendering pipeline name
  75824. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75825. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  75826. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  75827. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75828. */
  75829. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  75830. if (originalPostProcess === void 0) { originalPostProcess = null; }
  75831. var _this = _super.call(this, scene.getEngine(), name) || this;
  75832. _this.downSampleX4PostProcess = null;
  75833. _this.brightPassPostProcess = null;
  75834. _this.blurHPostProcesses = [];
  75835. _this.blurVPostProcesses = [];
  75836. _this.textureAdderPostProcess = null;
  75837. _this.volumetricLightPostProcess = null;
  75838. _this.volumetricLightSmoothXPostProcess = null;
  75839. _this.volumetricLightSmoothYPostProcess = null;
  75840. _this.volumetricLightMergePostProces = null;
  75841. _this.volumetricLightFinalPostProcess = null;
  75842. _this.luminancePostProcess = null;
  75843. _this.luminanceDownSamplePostProcesses = [];
  75844. _this.hdrPostProcess = null;
  75845. _this.textureAdderFinalPostProcess = null;
  75846. _this.lensFlareFinalPostProcess = null;
  75847. _this.hdrFinalPostProcess = null;
  75848. _this.lensFlarePostProcess = null;
  75849. _this.lensFlareComposePostProcess = null;
  75850. _this.motionBlurPostProcess = null;
  75851. _this.depthOfFieldPostProcess = null;
  75852. // Values
  75853. _this.brightThreshold = 1.0;
  75854. _this.blurWidth = 512.0;
  75855. _this.horizontalBlur = false;
  75856. _this.exposure = 1.0;
  75857. _this.lensTexture = null;
  75858. _this.volumetricLightCoefficient = 0.2;
  75859. _this.volumetricLightPower = 4.0;
  75860. _this.volumetricLightBlurScale = 64.0;
  75861. _this.sourceLight = null;
  75862. _this.hdrMinimumLuminance = 1.0;
  75863. _this.hdrDecreaseRate = 0.5;
  75864. _this.hdrIncreaseRate = 0.5;
  75865. _this.lensColorTexture = null;
  75866. _this.lensFlareStrength = 20.0;
  75867. _this.lensFlareGhostDispersal = 1.4;
  75868. _this.lensFlareHaloWidth = 0.7;
  75869. _this.lensFlareDistortionStrength = 16.0;
  75870. _this.lensStarTexture = null;
  75871. _this.lensFlareDirtTexture = null;
  75872. _this.depthOfFieldDistance = 10.0;
  75873. _this.depthOfFieldBlurWidth = 64.0;
  75874. _this.motionStrength = 1.0;
  75875. // IAnimatable
  75876. _this.animations = [];
  75877. _this._currentDepthOfFieldSource = null;
  75878. _this._hdrCurrentLuminance = 1.0;
  75879. // Getters and setters
  75880. _this._bloomEnabled = true;
  75881. _this._depthOfFieldEnabled = false;
  75882. _this._vlsEnabled = false;
  75883. _this._lensFlareEnabled = false;
  75884. _this._hdrEnabled = false;
  75885. _this._motionBlurEnabled = false;
  75886. _this._motionBlurSamples = 64.0;
  75887. _this._volumetricLightStepsCount = 50.0;
  75888. _this._cameras = cameras || [];
  75889. // Initialize
  75890. _this._scene = scene;
  75891. _this._basePostProcess = originalPostProcess;
  75892. _this._ratio = ratio;
  75893. // Misc
  75894. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75895. // Finish
  75896. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75897. _this._buildPipeline();
  75898. return _this;
  75899. }
  75900. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  75901. get: function () {
  75902. return this._bloomEnabled;
  75903. },
  75904. set: function (enabled) {
  75905. if (this._bloomEnabled === enabled) {
  75906. return;
  75907. }
  75908. this._bloomEnabled = enabled;
  75909. this._buildPipeline();
  75910. },
  75911. enumerable: true,
  75912. configurable: true
  75913. });
  75914. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  75915. get: function () {
  75916. return this._depthOfFieldEnabled;
  75917. },
  75918. set: function (enabled) {
  75919. if (this._depthOfFieldEnabled === enabled) {
  75920. return;
  75921. }
  75922. this._depthOfFieldEnabled = enabled;
  75923. this._buildPipeline();
  75924. },
  75925. enumerable: true,
  75926. configurable: true
  75927. });
  75928. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  75929. get: function () {
  75930. return this._lensFlareEnabled;
  75931. },
  75932. set: function (enabled) {
  75933. if (this._lensFlareEnabled === enabled) {
  75934. return;
  75935. }
  75936. this._lensFlareEnabled = enabled;
  75937. this._buildPipeline();
  75938. },
  75939. enumerable: true,
  75940. configurable: true
  75941. });
  75942. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  75943. get: function () {
  75944. return this._hdrEnabled;
  75945. },
  75946. set: function (enabled) {
  75947. if (this._hdrEnabled === enabled) {
  75948. return;
  75949. }
  75950. this._hdrEnabled = enabled;
  75951. this._buildPipeline();
  75952. },
  75953. enumerable: true,
  75954. configurable: true
  75955. });
  75956. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  75957. get: function () {
  75958. return this._vlsEnabled;
  75959. },
  75960. set: function (enabled) {
  75961. if (this._vlsEnabled === enabled) {
  75962. return;
  75963. }
  75964. if (enabled) {
  75965. var geometry = this._scene.enableGeometryBufferRenderer();
  75966. if (!geometry) {
  75967. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  75968. return;
  75969. }
  75970. }
  75971. this._vlsEnabled = enabled;
  75972. this._buildPipeline();
  75973. },
  75974. enumerable: true,
  75975. configurable: true
  75976. });
  75977. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  75978. get: function () {
  75979. return this._motionBlurEnabled;
  75980. },
  75981. set: function (enabled) {
  75982. if (this._motionBlurEnabled === enabled) {
  75983. return;
  75984. }
  75985. this._motionBlurEnabled = enabled;
  75986. this._buildPipeline();
  75987. },
  75988. enumerable: true,
  75989. configurable: true
  75990. });
  75991. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  75992. get: function () {
  75993. return this._volumetricLightStepsCount;
  75994. },
  75995. set: function (count) {
  75996. if (this.volumetricLightPostProcess) {
  75997. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  75998. }
  75999. this._volumetricLightStepsCount = count;
  76000. },
  76001. enumerable: true,
  76002. configurable: true
  76003. });
  76004. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  76005. get: function () {
  76006. return this._motionBlurSamples;
  76007. },
  76008. set: function (samples) {
  76009. if (this.motionBlurPostProcess) {
  76010. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  76011. }
  76012. this._motionBlurSamples = samples;
  76013. },
  76014. enumerable: true,
  76015. configurable: true
  76016. });
  76017. StandardRenderingPipeline.prototype._buildPipeline = function () {
  76018. var _this = this;
  76019. var ratio = this._ratio;
  76020. var scene = this._scene;
  76021. this._disposePostProcesses();
  76022. this._reset();
  76023. // Create pass post-process
  76024. if (!this._basePostProcess) {
  76025. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  76026. this.originalPostProcess.onApply = function (effect) {
  76027. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  76028. };
  76029. }
  76030. else {
  76031. this.originalPostProcess = this._basePostProcess;
  76032. }
  76033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  76034. this._currentDepthOfFieldSource = this.originalPostProcess;
  76035. if (this._bloomEnabled) {
  76036. // Create down sample X4 post-process
  76037. this._createDownSampleX4PostProcess(scene, ratio / 2);
  76038. // Create bright pass post-process
  76039. this._createBrightPassPostProcess(scene, ratio / 2);
  76040. // Create gaussian blur post-processes (down sampling blurs)
  76041. this._createBlurPostProcesses(scene, ratio / 4, 1);
  76042. // Create texture adder post-process
  76043. this._createTextureAdderPostProcess(scene, ratio);
  76044. // Create depth-of-field source post-process
  76045. 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);
  76046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  76047. }
  76048. if (this._vlsEnabled) {
  76049. // Create volumetric light
  76050. this._createVolumetricLightPostProcess(scene, ratio);
  76051. // Create volumetric light final post-process
  76052. 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);
  76053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  76054. }
  76055. if (this._lensFlareEnabled) {
  76056. // Create lens flare post-process
  76057. this._createLensFlarePostProcess(scene, ratio);
  76058. // Create depth-of-field source post-process post lens-flare and disable it now
  76059. 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);
  76060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  76061. }
  76062. if (this._hdrEnabled) {
  76063. // Create luminance
  76064. this._createLuminancePostProcesses(scene, this._floatTextureType);
  76065. // Create HDR
  76066. this._createHdrPostProcess(scene, ratio);
  76067. // Create depth-of-field source post-process post hdr and disable it now
  76068. 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);
  76069. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  76070. }
  76071. if (this._depthOfFieldEnabled) {
  76072. // Create gaussian blur used by depth-of-field
  76073. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  76074. // Create depth-of-field post-process
  76075. this._createDepthOfFieldPostProcess(scene, ratio);
  76076. }
  76077. if (this._motionBlurEnabled) {
  76078. // Create motion blur post-process
  76079. this._createMotionBlurPostProcess(scene, ratio);
  76080. }
  76081. if (this._cameras !== null) {
  76082. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76083. }
  76084. };
  76085. // Down Sample X4 Post-Processs
  76086. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  76087. var _this = this;
  76088. var downSampleX4Offsets = new Array(32);
  76089. 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);
  76090. this.downSampleX4PostProcess.onApply = function (effect) {
  76091. var id = 0;
  76092. var width = _this.downSampleX4PostProcess.width;
  76093. var height = _this.downSampleX4PostProcess.height;
  76094. for (var i = -2; i < 2; i++) {
  76095. for (var j = -2; j < 2; j++) {
  76096. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  76097. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  76098. id += 2;
  76099. }
  76100. }
  76101. effect.setArray2("dsOffsets", downSampleX4Offsets);
  76102. };
  76103. // Add to pipeline
  76104. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  76105. };
  76106. // Brightpass Post-Process
  76107. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  76108. var _this = this;
  76109. var brightOffsets = new Array(8);
  76110. 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);
  76111. this.brightPassPostProcess.onApply = function (effect) {
  76112. var sU = (1.0 / _this.brightPassPostProcess.width);
  76113. var sV = (1.0 / _this.brightPassPostProcess.height);
  76114. brightOffsets[0] = -0.5 * sU;
  76115. brightOffsets[1] = 0.5 * sV;
  76116. brightOffsets[2] = 0.5 * sU;
  76117. brightOffsets[3] = 0.5 * sV;
  76118. brightOffsets[4] = -0.5 * sU;
  76119. brightOffsets[5] = -0.5 * sV;
  76120. brightOffsets[6] = 0.5 * sU;
  76121. brightOffsets[7] = -0.5 * sV;
  76122. effect.setArray2("dsOffsets", brightOffsets);
  76123. effect.setFloat("brightThreshold", _this.brightThreshold);
  76124. };
  76125. // Add to pipeline
  76126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  76127. };
  76128. // Create blur H&V post-processes
  76129. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  76130. var _this = this;
  76131. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  76132. var engine = scene.getEngine();
  76133. 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);
  76134. 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);
  76135. blurX.onActivateObservable.add(function () {
  76136. var dw = blurX.width / engine.getRenderWidth();
  76137. blurX.kernel = _this[blurWidthKey] * dw;
  76138. });
  76139. blurY.onActivateObservable.add(function () {
  76140. var dw = blurY.height / engine.getRenderHeight();
  76141. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  76142. });
  76143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  76144. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  76145. this.blurHPostProcesses.push(blurX);
  76146. this.blurVPostProcesses.push(blurY);
  76147. };
  76148. // Create texture adder post-process
  76149. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  76150. var _this = this;
  76151. 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);
  76152. this.textureAdderPostProcess.onApply = function (effect) {
  76153. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  76154. effect.setTexture("lensSampler", _this.lensTexture);
  76155. effect.setFloat("exposure", _this.exposure);
  76156. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  76157. };
  76158. // Add to pipeline
  76159. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  76160. };
  76161. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  76162. var _this = this;
  76163. var geometryRenderer = scene.enableGeometryBufferRenderer();
  76164. geometryRenderer.enablePosition = true;
  76165. var geometry = geometryRenderer.getGBuffer();
  76166. // Base post-process
  76167. 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));
  76168. var depthValues = BABYLON.Vector2.Zero();
  76169. this.volumetricLightPostProcess.onApply = function (effect) {
  76170. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  76171. var generator = _this.sourceLight.getShadowGenerator();
  76172. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  76173. effect.setTexture("positionSampler", geometry.textures[2]);
  76174. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  76175. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  76176. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  76177. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  76178. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  76179. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  76180. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  76181. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  76182. effect.setVector2("depthValues", depthValues);
  76183. }
  76184. };
  76185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  76186. // Smooth
  76187. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  76188. // Merge
  76189. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  76190. this.volumetricLightMergePostProces.onApply = function (effect) {
  76191. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  76192. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  76193. };
  76194. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  76195. };
  76196. // Create luminance
  76197. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  76198. var _this = this;
  76199. // Create luminance
  76200. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  76201. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  76202. var offsets = [];
  76203. this.luminancePostProcess.onApply = function (effect) {
  76204. var sU = (1.0 / _this.luminancePostProcess.width);
  76205. var sV = (1.0 / _this.luminancePostProcess.height);
  76206. offsets[0] = -0.5 * sU;
  76207. offsets[1] = 0.5 * sV;
  76208. offsets[2] = 0.5 * sU;
  76209. offsets[3] = 0.5 * sV;
  76210. offsets[4] = -0.5 * sU;
  76211. offsets[5] = -0.5 * sV;
  76212. offsets[6] = 0.5 * sU;
  76213. offsets[7] = -0.5 * sV;
  76214. effect.setArray2("lumOffsets", offsets);
  76215. };
  76216. // Add to pipeline
  76217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  76218. // Create down sample luminance
  76219. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  76220. var size = Math.pow(3, i);
  76221. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  76222. if (i === 0) {
  76223. defines += "#define FINAL_DOWN_SAMPLER";
  76224. }
  76225. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  76226. this.luminanceDownSamplePostProcesses.push(postProcess);
  76227. }
  76228. // Create callbacks and add effects
  76229. var lastLuminance = this.luminancePostProcess;
  76230. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  76231. var downSampleOffsets = new Array(18);
  76232. pp.onApply = function (effect) {
  76233. if (!lastLuminance) {
  76234. return;
  76235. }
  76236. var id = 0;
  76237. for (var x = -1; x < 2; x++) {
  76238. for (var y = -1; y < 2; y++) {
  76239. downSampleOffsets[id] = x / lastLuminance.width;
  76240. downSampleOffsets[id + 1] = y / lastLuminance.height;
  76241. id += 2;
  76242. }
  76243. }
  76244. effect.setArray2("dsOffsets", downSampleOffsets);
  76245. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  76246. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76247. lastLuminance = _this.luminancePostProcess;
  76248. }
  76249. else {
  76250. lastLuminance = pp;
  76251. }
  76252. };
  76253. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  76254. pp.onAfterRender = function (effect) {
  76255. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  76256. 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);
  76257. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  76258. };
  76259. }
  76260. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  76261. });
  76262. };
  76263. // Create HDR post-process
  76264. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  76265. var _this = this;
  76266. 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);
  76267. var outputLiminance = 1;
  76268. var time = 0;
  76269. var lastTime = 0;
  76270. this.hdrPostProcess.onApply = function (effect) {
  76271. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  76272. time += scene.getEngine().getDeltaTime();
  76273. if (outputLiminance < 0) {
  76274. outputLiminance = _this._hdrCurrentLuminance;
  76275. }
  76276. else {
  76277. var dt = (lastTime - time) / 1000.0;
  76278. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  76279. outputLiminance += _this.hdrDecreaseRate * dt;
  76280. }
  76281. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  76282. outputLiminance -= _this.hdrIncreaseRate * dt;
  76283. }
  76284. else {
  76285. outputLiminance = _this._hdrCurrentLuminance;
  76286. }
  76287. }
  76288. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  76289. effect.setFloat("averageLuminance", outputLiminance);
  76290. lastTime = time;
  76291. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  76292. };
  76293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  76294. };
  76295. // Create lens flare post-process
  76296. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  76297. var _this = this;
  76298. 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);
  76299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  76300. this._createBlurPostProcesses(scene, ratio / 4, 2);
  76301. 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);
  76302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  76303. var resolution = new BABYLON.Vector2(0, 0);
  76304. // Lens flare
  76305. this.lensFlarePostProcess.onApply = function (effect) {
  76306. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  76307. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  76308. effect.setFloat("strength", _this.lensFlareStrength);
  76309. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  76310. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  76311. // Shift
  76312. resolution.x = _this.lensFlarePostProcess.width;
  76313. resolution.y = _this.lensFlarePostProcess.height;
  76314. effect.setVector2("resolution", resolution);
  76315. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  76316. };
  76317. // Compose
  76318. 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);
  76319. 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);
  76320. this.lensFlareComposePostProcess.onApply = function (effect) {
  76321. if (!_this._scene.activeCamera) {
  76322. return;
  76323. }
  76324. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76325. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  76326. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  76327. // Lens start rotation matrix
  76328. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  76329. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  76330. 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));
  76331. camRot *= 4.0;
  76332. 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);
  76333. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  76334. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  76335. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  76336. };
  76337. };
  76338. // Create depth-of-field post-process
  76339. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  76340. var _this = this;
  76341. 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);
  76342. this.depthOfFieldPostProcess.onApply = function (effect) {
  76343. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  76344. effect.setTexture("depthSampler", _this._getDepthTexture());
  76345. effect.setFloat("distance", _this.depthOfFieldDistance);
  76346. };
  76347. // Add to pipeline
  76348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  76349. };
  76350. // Create motion blur post-process
  76351. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  76352. var _this = this;
  76353. 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);
  76354. var motionScale = 0;
  76355. var prevViewProjection = BABYLON.Matrix.Identity();
  76356. var invViewProjection = BABYLON.Matrix.Identity();
  76357. var viewProjection = BABYLON.Matrix.Identity();
  76358. var screenSize = BABYLON.Vector2.Zero();
  76359. this.motionBlurPostProcess.onApply = function (effect) {
  76360. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  76361. viewProjection.invertToRef(invViewProjection);
  76362. effect.setMatrix("inverseViewProjection", invViewProjection);
  76363. effect.setMatrix("prevViewProjection", prevViewProjection);
  76364. prevViewProjection = viewProjection;
  76365. screenSize.x = _this.motionBlurPostProcess.width;
  76366. screenSize.y = _this.motionBlurPostProcess.height;
  76367. effect.setVector2("screenSize", screenSize);
  76368. motionScale = scene.getEngine().getFps() / 60.0;
  76369. effect.setFloat("motionScale", motionScale);
  76370. effect.setFloat("motionStrength", _this.motionStrength);
  76371. effect.setTexture("depthSampler", _this._getDepthTexture());
  76372. };
  76373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  76374. };
  76375. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  76376. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  76377. var renderer = this._scene.enableGeometryBufferRenderer();
  76378. return renderer.getGBuffer().textures[0];
  76379. }
  76380. return this._scene.enableDepthRenderer().getDepthMap();
  76381. };
  76382. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  76383. for (var i = 0; i < this._cameras.length; i++) {
  76384. var camera = this._cameras[i];
  76385. if (this.originalPostProcess) {
  76386. this.originalPostProcess.dispose(camera);
  76387. }
  76388. if (this.downSampleX4PostProcess) {
  76389. this.downSampleX4PostProcess.dispose(camera);
  76390. }
  76391. if (this.brightPassPostProcess) {
  76392. this.brightPassPostProcess.dispose(camera);
  76393. }
  76394. if (this.textureAdderPostProcess) {
  76395. this.textureAdderPostProcess.dispose(camera);
  76396. }
  76397. if (this.textureAdderFinalPostProcess) {
  76398. this.textureAdderFinalPostProcess.dispose(camera);
  76399. }
  76400. if (this.volumetricLightPostProcess) {
  76401. this.volumetricLightPostProcess.dispose(camera);
  76402. }
  76403. if (this.volumetricLightSmoothXPostProcess) {
  76404. this.volumetricLightSmoothXPostProcess.dispose(camera);
  76405. }
  76406. if (this.volumetricLightSmoothYPostProcess) {
  76407. this.volumetricLightSmoothYPostProcess.dispose(camera);
  76408. }
  76409. if (this.volumetricLightMergePostProces) {
  76410. this.volumetricLightMergePostProces.dispose(camera);
  76411. }
  76412. if (this.volumetricLightFinalPostProcess) {
  76413. this.volumetricLightFinalPostProcess.dispose(camera);
  76414. }
  76415. if (this.lensFlarePostProcess) {
  76416. this.lensFlarePostProcess.dispose(camera);
  76417. }
  76418. if (this.lensFlareComposePostProcess) {
  76419. this.lensFlareComposePostProcess.dispose(camera);
  76420. }
  76421. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  76422. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  76423. }
  76424. if (this.luminancePostProcess) {
  76425. this.luminancePostProcess.dispose(camera);
  76426. }
  76427. if (this.hdrPostProcess) {
  76428. this.hdrPostProcess.dispose(camera);
  76429. }
  76430. if (this.hdrFinalPostProcess) {
  76431. this.hdrFinalPostProcess.dispose(camera);
  76432. }
  76433. if (this.depthOfFieldPostProcess) {
  76434. this.depthOfFieldPostProcess.dispose(camera);
  76435. }
  76436. if (this.motionBlurPostProcess) {
  76437. this.motionBlurPostProcess.dispose(camera);
  76438. }
  76439. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  76440. this.blurHPostProcesses[j].dispose(camera);
  76441. }
  76442. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  76443. this.blurVPostProcesses[j].dispose(camera);
  76444. }
  76445. }
  76446. this.originalPostProcess = null;
  76447. this.downSampleX4PostProcess = null;
  76448. this.brightPassPostProcess = null;
  76449. this.textureAdderPostProcess = null;
  76450. this.textureAdderFinalPostProcess = null;
  76451. this.volumetricLightPostProcess = null;
  76452. this.volumetricLightSmoothXPostProcess = null;
  76453. this.volumetricLightSmoothYPostProcess = null;
  76454. this.volumetricLightMergePostProces = null;
  76455. this.volumetricLightFinalPostProcess = null;
  76456. this.lensFlarePostProcess = null;
  76457. this.lensFlareComposePostProcess = null;
  76458. this.luminancePostProcess = null;
  76459. this.hdrPostProcess = null;
  76460. this.hdrFinalPostProcess = null;
  76461. this.depthOfFieldPostProcess = null;
  76462. this.motionBlurPostProcess = null;
  76463. this.luminanceDownSamplePostProcesses = [];
  76464. this.blurHPostProcesses = [];
  76465. this.blurVPostProcesses = [];
  76466. };
  76467. /**
  76468. * Dispose of the pipeline and stop all post processes
  76469. */
  76470. StandardRenderingPipeline.prototype.dispose = function () {
  76471. this._disposePostProcesses();
  76472. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76473. _super.prototype.dispose.call(this);
  76474. };
  76475. /**
  76476. * Serialize the rendering pipeline (Used when exporting)
  76477. * @returns the serialized object
  76478. */
  76479. StandardRenderingPipeline.prototype.serialize = function () {
  76480. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76481. if (this.sourceLight) {
  76482. serializationObject.sourceLightId = this.sourceLight.id;
  76483. }
  76484. serializationObject.customType = "StandardRenderingPipeline";
  76485. return serializationObject;
  76486. };
  76487. /**
  76488. * Parse the serialized pipeline
  76489. * @param source Source pipeline.
  76490. * @param scene The scene to load the pipeline to.
  76491. * @param rootUrl The URL of the serialized pipeline.
  76492. * @returns An instantiated pipeline from the serialized object.
  76493. */
  76494. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76495. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76496. if (source.sourceLightId) {
  76497. p.sourceLight = scene.getLightByID(source.sourceLightId);
  76498. }
  76499. return p;
  76500. };
  76501. // Luminance steps
  76502. StandardRenderingPipeline.LuminanceSteps = 6;
  76503. __decorate([
  76504. BABYLON.serialize()
  76505. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  76506. __decorate([
  76507. BABYLON.serialize()
  76508. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  76509. __decorate([
  76510. BABYLON.serialize()
  76511. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  76512. __decorate([
  76513. BABYLON.serialize()
  76514. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  76515. __decorate([
  76516. BABYLON.serializeAsTexture("lensTexture")
  76517. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  76530. __decorate([
  76531. BABYLON.serialize()
  76532. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  76533. __decorate([
  76534. BABYLON.serialize()
  76535. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  76536. __decorate([
  76537. BABYLON.serializeAsTexture("lensColorTexture")
  76538. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  76539. __decorate([
  76540. BABYLON.serialize()
  76541. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  76542. __decorate([
  76543. BABYLON.serialize()
  76544. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  76545. __decorate([
  76546. BABYLON.serialize()
  76547. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  76548. __decorate([
  76549. BABYLON.serialize()
  76550. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  76551. __decorate([
  76552. BABYLON.serializeAsTexture("lensStarTexture")
  76553. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  76554. __decorate([
  76555. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  76556. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  76557. __decorate([
  76558. BABYLON.serialize()
  76559. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  76560. __decorate([
  76561. BABYLON.serialize()
  76562. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  76563. __decorate([
  76564. BABYLON.serialize()
  76565. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  76566. __decorate([
  76567. BABYLON.serialize()
  76568. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  76569. __decorate([
  76570. BABYLON.serialize()
  76571. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  76572. __decorate([
  76573. BABYLON.serialize()
  76574. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  76575. __decorate([
  76576. BABYLON.serialize()
  76577. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  76578. __decorate([
  76579. BABYLON.serialize()
  76580. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  76581. __decorate([
  76582. BABYLON.serialize()
  76583. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  76584. __decorate([
  76585. BABYLON.serialize()
  76586. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  76587. __decorate([
  76588. BABYLON.serialize()
  76589. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  76590. __decorate([
  76591. BABYLON.serialize()
  76592. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  76593. return StandardRenderingPipeline;
  76594. }(BABYLON.PostProcessRenderPipeline));
  76595. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  76596. })(BABYLON || (BABYLON = {}));
  76597. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  76598. var BABYLON;
  76599. (function (BABYLON) {
  76600. var FxaaPostProcess = /** @class */ (function (_super) {
  76601. __extends(FxaaPostProcess, _super);
  76602. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76603. if (camera === void 0) { camera = null; }
  76604. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76605. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  76606. var defines = _this._getDefines();
  76607. _this.updateEffect(defines);
  76608. _this.onApplyObservable.add(function (effect) {
  76609. var texelSize = _this.texelSize;
  76610. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  76611. });
  76612. return _this;
  76613. }
  76614. FxaaPostProcess.prototype._getDefines = function () {
  76615. var engine = this.getEngine();
  76616. if (!engine) {
  76617. return null;
  76618. }
  76619. var glInfo = engine.getGlInfo();
  76620. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  76621. return "#define MALI 1\n";
  76622. }
  76623. return null;
  76624. };
  76625. return FxaaPostProcess;
  76626. }(BABYLON.PostProcess));
  76627. BABYLON.FxaaPostProcess = FxaaPostProcess;
  76628. })(BABYLON || (BABYLON = {}));
  76629. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  76630. var BABYLON;
  76631. (function (BABYLON) {
  76632. /**
  76633. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  76634. */
  76635. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  76636. __extends(ChromaticAberrationPostProcess, _super);
  76637. /**
  76638. * Creates a new instance ChromaticAberrationPostProcess
  76639. * @param name The name of the effect.
  76640. * @param screenWidth The width of the screen to apply the effect on.
  76641. * @param screenHeight The height of the screen to apply the effect on.
  76642. * @param options The required width/height ratio to downsize to before computing the render pass.
  76643. * @param camera The camera to apply the render pass to.
  76644. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76645. * @param engine The engine which the post process will be applied. (default: current engine)
  76646. * @param reusable If the post process can be reused on the same frame. (default: false)
  76647. * @param textureType Type of textures used when performing the post process. (default: 0)
  76648. * @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)
  76649. */
  76650. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76652. if (blockCompilation === void 0) { blockCompilation = false; }
  76653. 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;
  76654. /**
  76655. * The amount of seperation of rgb channels (default: 30)
  76656. */
  76657. _this.aberrationAmount = 30;
  76658. /**
  76659. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  76660. */
  76661. _this.radialIntensity = 0;
  76662. /**
  76663. * 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))
  76664. */
  76665. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  76666. /**
  76667. * 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))
  76668. */
  76669. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  76670. _this.onApplyObservable.add(function (effect) {
  76671. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  76672. effect.setFloat('screen_width', screenWidth);
  76673. effect.setFloat('screen_height', screenHeight);
  76674. effect.setFloat('radialIntensity', _this.radialIntensity);
  76675. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  76676. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  76677. });
  76678. return _this;
  76679. }
  76680. return ChromaticAberrationPostProcess;
  76681. }(BABYLON.PostProcess));
  76682. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  76683. })(BABYLON || (BABYLON = {}));
  76684. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  76685. var BABYLON;
  76686. (function (BABYLON) {
  76687. /**
  76688. * The GrainPostProcess adds noise to the image at mid luminance levels
  76689. */
  76690. var GrainPostProcess = /** @class */ (function (_super) {
  76691. __extends(GrainPostProcess, _super);
  76692. /**
  76693. * Creates a new instance of @see GrainPostProcess
  76694. * @param name The name of the effect.
  76695. * @param options The required width/height ratio to downsize to before computing the render pass.
  76696. * @param camera The camera to apply the render pass to.
  76697. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76698. * @param engine The engine which the post process will be applied. (default: current engine)
  76699. * @param reusable If the post process can be reused on the same frame. (default: false)
  76700. * @param textureType Type of textures used when performing the post process. (default: 0)
  76701. * @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)
  76702. */
  76703. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76704. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76705. if (blockCompilation === void 0) { blockCompilation = false; }
  76706. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76707. /**
  76708. * The intensity of the grain added (default: 30)
  76709. */
  76710. _this.intensity = 30;
  76711. /**
  76712. * If the grain should be randomized on every frame
  76713. */
  76714. _this.animated = false;
  76715. _this.onApplyObservable.add(function (effect) {
  76716. effect.setFloat('intensity', _this.intensity);
  76717. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  76718. });
  76719. return _this;
  76720. }
  76721. return GrainPostProcess;
  76722. }(BABYLON.PostProcess));
  76723. BABYLON.GrainPostProcess = GrainPostProcess;
  76724. })(BABYLON || (BABYLON = {}));
  76725. //# sourceMappingURL=babylon.grainPostProcess.js.map
  76726. var BABYLON;
  76727. (function (BABYLON) {
  76728. /**
  76729. * The SharpenPostProcess applies a sharpen kernel to every pixel
  76730. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76731. */
  76732. var SharpenPostProcess = /** @class */ (function (_super) {
  76733. __extends(SharpenPostProcess, _super);
  76734. /**
  76735. * Creates a new instance ConvolutionPostProcess
  76736. * @param name The name of the effect.
  76737. * @param options The required width/height ratio to downsize to before computing the render pass.
  76738. * @param camera The camera to apply the render pass to.
  76739. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76740. * @param engine The engine which the post process will be applied. (default: current engine)
  76741. * @param reusable If the post process can be reused on the same frame. (default: false)
  76742. * @param textureType Type of textures used when performing the post process. (default: 0)
  76743. * @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)
  76744. */
  76745. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76746. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76747. if (blockCompilation === void 0) { blockCompilation = false; }
  76748. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76749. /**
  76750. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  76751. */
  76752. _this.colorAmount = 1.0;
  76753. /**
  76754. * How much sharpness should be applied (default: 0.3)
  76755. */
  76756. _this.edgeAmount = 0.3;
  76757. _this.onApply = function (effect) {
  76758. effect.setFloat2("screenSize", _this.width, _this.height);
  76759. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  76760. };
  76761. return _this;
  76762. }
  76763. return SharpenPostProcess;
  76764. }(BABYLON.PostProcess));
  76765. BABYLON.SharpenPostProcess = SharpenPostProcess;
  76766. })(BABYLON || (BABYLON = {}));
  76767. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  76768. var BABYLON;
  76769. (function (BABYLON) {
  76770. /**
  76771. * The Blur Post Process which blurs an image based on a kernel and direction.
  76772. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  76773. */
  76774. var BlurPostProcess = /** @class */ (function (_super) {
  76775. __extends(BlurPostProcess, _super);
  76776. /**
  76777. * Creates a new instance BlurPostProcess
  76778. * @param name The name of the effect.
  76779. * @param direction The direction in which to blur the image.
  76780. * @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.
  76781. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  76782. * @param camera The camera to apply the render pass to.
  76783. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76784. * @param engine The engine which the post process will be applied. (default: current engine)
  76785. * @param reusable If the post process can be reused on the same frame. (default: false)
  76786. * @param textureType Type of textures used when performing the post process. (default: 0)
  76787. * @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)
  76788. */
  76789. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  76790. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76791. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76792. if (defines === void 0) { defines = ""; }
  76793. if (blockCompilation === void 0) { blockCompilation = false; }
  76794. 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;
  76795. _this.direction = direction;
  76796. _this.blockCompilation = blockCompilation;
  76797. _this._packedFloat = false;
  76798. _this._staticDefines = "";
  76799. _this._staticDefines = defines;
  76800. _this.onApplyObservable.add(function (effect) {
  76801. if (_this._outputTexture) {
  76802. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  76803. }
  76804. else {
  76805. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  76806. }
  76807. });
  76808. _this.kernel = kernel;
  76809. return _this;
  76810. }
  76811. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  76812. /**
  76813. * Gets the length in pixels of the blur sample region
  76814. */
  76815. get: function () {
  76816. return this._idealKernel;
  76817. },
  76818. /**
  76819. * Sets the length in pixels of the blur sample region
  76820. */
  76821. set: function (v) {
  76822. if (this._idealKernel === v) {
  76823. return;
  76824. }
  76825. v = Math.max(v, 1);
  76826. this._idealKernel = v;
  76827. this._kernel = this._nearestBestKernel(v);
  76828. if (!this.blockCompilation) {
  76829. this._updateParameters();
  76830. }
  76831. },
  76832. enumerable: true,
  76833. configurable: true
  76834. });
  76835. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  76836. /**
  76837. * Gets wether or not the blur is unpacking/repacking floats
  76838. */
  76839. get: function () {
  76840. return this._packedFloat;
  76841. },
  76842. /**
  76843. * Sets wether or not the blur needs to unpack/repack floats
  76844. */
  76845. set: function (v) {
  76846. if (this._packedFloat === v) {
  76847. return;
  76848. }
  76849. this._packedFloat = v;
  76850. if (!this.blockCompilation) {
  76851. this._updateParameters();
  76852. }
  76853. },
  76854. enumerable: true,
  76855. configurable: true
  76856. });
  76857. /**
  76858. * Updates the effect with the current post process compile time values and recompiles the shader.
  76859. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76860. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76861. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76862. * @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
  76863. * @param onCompiled Called when the shader has been compiled.
  76864. * @param onError Called if there is an error when compiling a shader.
  76865. */
  76866. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76867. if (defines === void 0) { defines = null; }
  76868. if (uniforms === void 0) { uniforms = null; }
  76869. if (samplers === void 0) { samplers = null; }
  76870. this._updateParameters(onCompiled, onError);
  76871. };
  76872. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  76873. // Generate sampling offsets and weights
  76874. var N = this._kernel;
  76875. var centerIndex = (N - 1) / 2;
  76876. // Generate Gaussian sampling weights over kernel
  76877. var offsets = [];
  76878. var weights = [];
  76879. var totalWeight = 0;
  76880. for (var i = 0; i < N; i++) {
  76881. var u = i / (N - 1);
  76882. var w = this._gaussianWeight(u * 2.0 - 1);
  76883. offsets[i] = (i - centerIndex);
  76884. weights[i] = w;
  76885. totalWeight += w;
  76886. }
  76887. // Normalize weights
  76888. for (var i = 0; i < weights.length; i++) {
  76889. weights[i] /= totalWeight;
  76890. }
  76891. // Optimize: combine samples to take advantage of hardware linear sampling
  76892. // Walk from left to center, combining pairs (symmetrically)
  76893. var linearSamplingWeights = [];
  76894. var linearSamplingOffsets = [];
  76895. var linearSamplingMap = [];
  76896. for (var i = 0; i <= centerIndex; i += 2) {
  76897. var j = Math.min(i + 1, Math.floor(centerIndex));
  76898. var singleCenterSample = i === j;
  76899. if (singleCenterSample) {
  76900. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76901. }
  76902. else {
  76903. var sharedCell = j === centerIndex;
  76904. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  76905. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  76906. if (offsetLinear === 0) {
  76907. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  76908. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  76909. }
  76910. else {
  76911. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  76912. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  76913. }
  76914. }
  76915. }
  76916. for (var i = 0; i < linearSamplingMap.length; i++) {
  76917. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  76918. linearSamplingWeights[i] = linearSamplingMap[i].w;
  76919. }
  76920. // Replace with optimized
  76921. offsets = linearSamplingOffsets;
  76922. weights = linearSamplingWeights;
  76923. // Generate shaders
  76924. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  76925. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  76926. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  76927. var defines = "";
  76928. defines += this._staticDefines;
  76929. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  76930. if (this._staticDefines.indexOf("DOF") != -1) {
  76931. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  76932. varyingCount--;
  76933. }
  76934. for (var i = 0; i < varyingCount; i++) {
  76935. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  76936. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  76937. }
  76938. var depCount = 0;
  76939. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  76940. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  76941. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  76942. depCount++;
  76943. }
  76944. if (this.packedFloat) {
  76945. defines += "#define PACKEDFLOAT 1";
  76946. }
  76947. this.blockCompilation = false;
  76948. _super.prototype.updateEffect.call(this, defines, null, null, {
  76949. varyingCount: varyingCount,
  76950. depCount: depCount
  76951. }, onCompiled, onError);
  76952. };
  76953. /**
  76954. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  76955. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  76956. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  76957. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  76958. * The gaps between physical kernels are compensated for in the weighting of the samples
  76959. * @param idealKernel Ideal blur kernel.
  76960. * @return Nearest best kernel.
  76961. */
  76962. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  76963. var v = Math.round(idealKernel);
  76964. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  76965. var k = _a[_i];
  76966. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  76967. return Math.max(k, 3);
  76968. }
  76969. }
  76970. return Math.max(v, 3);
  76971. };
  76972. /**
  76973. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  76974. * @param x The point on the Gaussian distribution to sample.
  76975. * @return the value of the Gaussian function at x.
  76976. */
  76977. BlurPostProcess.prototype._gaussianWeight = function (x) {
  76978. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  76979. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  76980. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  76981. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  76982. // truncated at around 1.3% of peak strength.
  76983. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  76984. var sigma = (1 / 3);
  76985. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  76986. var exponent = -((x * x) / (2.0 * sigma * sigma));
  76987. var weight = (1.0 / denominator) * Math.exp(exponent);
  76988. return weight;
  76989. };
  76990. /**
  76991. * Generates a string that can be used as a floating point number in GLSL.
  76992. * @param x Value to print.
  76993. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  76994. * @return GLSL float string.
  76995. */
  76996. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  76997. if (decimalFigures === void 0) { decimalFigures = 8; }
  76998. return x.toFixed(decimalFigures).replace(/0+$/, '');
  76999. };
  77000. return BlurPostProcess;
  77001. }(BABYLON.PostProcess));
  77002. BABYLON.BlurPostProcess = BlurPostProcess;
  77003. })(BABYLON || (BABYLON = {}));
  77004. //# sourceMappingURL=babylon.blurPostProcess.js.map
  77005. var BABYLON;
  77006. (function (BABYLON) {
  77007. /**
  77008. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  77009. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  77010. * based on samples that have a large difference in distance than the center pixel.
  77011. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77012. */
  77013. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  77014. __extends(DepthOfFieldBlurPostProcess, _super);
  77015. /**
  77016. * Creates a new instance CircleOfConfusionPostProcess
  77017. * @param name The name of the effect.
  77018. * @param scene The scene the effect belongs to.
  77019. * @param direction The direction the blur should be applied.
  77020. * @param kernel The size of the kernel used to blur.
  77021. * @param options The required width/height ratio to downsize to before computing the render pass.
  77022. * @param camera The camera to apply the render pass to.
  77023. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  77024. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  77025. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77026. * @param engine The engine which the post process will be applied. (default: current engine)
  77027. * @param reusable If the post process can be reused on the same frame. (default: false)
  77028. * @param textureType Type of textures used when performing the post process. (default: 0)
  77029. * @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)
  77030. */
  77031. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  77032. if (imageToBlur === void 0) { imageToBlur = null; }
  77033. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77035. if (blockCompilation === void 0) { blockCompilation = false; }
  77036. 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;
  77037. _this.direction = direction;
  77038. _this.onApplyObservable.add(function (effect) {
  77039. if (imageToBlur != null) {
  77040. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  77041. }
  77042. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77043. if (scene.activeCamera) {
  77044. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77045. }
  77046. });
  77047. return _this;
  77048. }
  77049. return DepthOfFieldBlurPostProcess;
  77050. }(BABYLON.BlurPostProcess));
  77051. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  77052. })(BABYLON || (BABYLON = {}));
  77053. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  77054. var BABYLON;
  77055. (function (BABYLON) {
  77056. /**
  77057. * Options to be set when merging outputs from the default pipeline.
  77058. */
  77059. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  77060. function DepthOfFieldMergePostProcessOptions() {
  77061. }
  77062. return DepthOfFieldMergePostProcessOptions;
  77063. }());
  77064. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  77065. /**
  77066. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77067. */
  77068. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  77069. __extends(DepthOfFieldMergePostProcess, _super);
  77070. /**
  77071. * Creates a new instance of DepthOfFieldMergePostProcess
  77072. * @param name The name of the effect.
  77073. * @param originalFromInput Post process which's input will be used for the merge.
  77074. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  77075. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  77076. * @param options The required width/height ratio to downsize to before computing the render pass.
  77077. * @param camera The camera to apply the render pass to.
  77078. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77079. * @param engine The engine which the post process will be applied. (default: current engine)
  77080. * @param reusable If the post process can be reused on the same frame. (default: false)
  77081. * @param textureType Type of textures used when performing the post process. (default: 0)
  77082. * @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)
  77083. */
  77084. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77085. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77086. if (blockCompilation === void 0) { blockCompilation = false; }
  77087. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77088. _this.blurSteps = blurSteps;
  77089. _this.onApplyObservable.add(function (effect) {
  77090. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77091. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  77092. blurSteps.forEach(function (step, index) {
  77093. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  77094. });
  77095. });
  77096. if (!blockCompilation) {
  77097. _this.updateEffect();
  77098. }
  77099. return _this;
  77100. }
  77101. /**
  77102. * Updates the effect with the current post process compile time values and recompiles the shader.
  77103. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  77104. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  77105. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  77106. * @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
  77107. * @param onCompiled Called when the shader has been compiled.
  77108. * @param onError Called if there is an error when compiling a shader.
  77109. */
  77110. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  77111. if (defines === void 0) { defines = null; }
  77112. if (uniforms === void 0) { uniforms = null; }
  77113. if (samplers === void 0) { samplers = null; }
  77114. if (!defines) {
  77115. defines = "";
  77116. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  77117. }
  77118. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  77119. };
  77120. return DepthOfFieldMergePostProcess;
  77121. }(BABYLON.PostProcess));
  77122. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  77123. })(BABYLON || (BABYLON = {}));
  77124. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  77125. var BABYLON;
  77126. (function (BABYLON) {
  77127. /**
  77128. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  77129. */
  77130. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  77131. __extends(CircleOfConfusionPostProcess, _super);
  77132. /**
  77133. * Creates a new instance CircleOfConfusionPostProcess
  77134. * @param name The name of the effect.
  77135. * @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.
  77136. * @param options The required width/height ratio to downsize to before computing the render pass.
  77137. * @param camera The camera to apply the render pass to.
  77138. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77139. * @param engine The engine which the post process will be applied. (default: current engine)
  77140. * @param reusable If the post process can be reused on the same frame. (default: false)
  77141. * @param textureType Type of textures used when performing the post process. (default: 0)
  77142. * @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)
  77143. */
  77144. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77145. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77146. if (blockCompilation === void 0) { blockCompilation = false; }
  77147. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77148. /**
  77149. * 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.
  77150. */
  77151. _this.lensSize = 50;
  77152. /**
  77153. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77154. */
  77155. _this.fStop = 1.4;
  77156. /**
  77157. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77158. */
  77159. _this.focusDistance = 2000;
  77160. /**
  77161. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  77162. */
  77163. _this.focalLength = 50;
  77164. _this._depthTexture = null;
  77165. _this._depthTexture = depthTexture;
  77166. _this.onApplyObservable.add(function (effect) {
  77167. if (!_this._depthTexture) {
  77168. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  77169. return;
  77170. }
  77171. effect.setTexture("depthSampler", _this._depthTexture);
  77172. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  77173. var aperture = _this.lensSize / _this.fStop;
  77174. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  77175. effect.setFloat('focusDistance', _this.focusDistance);
  77176. effect.setFloat('cocPrecalculation', cocPrecalculation);
  77177. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  77178. });
  77179. return _this;
  77180. }
  77181. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  77182. /**
  77183. * 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.
  77184. */
  77185. set: function (value) {
  77186. this._depthTexture = value;
  77187. },
  77188. enumerable: true,
  77189. configurable: true
  77190. });
  77191. return CircleOfConfusionPostProcess;
  77192. }(BABYLON.PostProcess));
  77193. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  77194. })(BABYLON || (BABYLON = {}));
  77195. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  77196. var BABYLON;
  77197. (function (BABYLON) {
  77198. /**
  77199. * Specifies the level of max blur that should be applied when using the depth of field effect
  77200. */
  77201. var DepthOfFieldEffectBlurLevel;
  77202. (function (DepthOfFieldEffectBlurLevel) {
  77203. /**
  77204. * Subtle blur
  77205. */
  77206. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  77207. /**
  77208. * Medium blur
  77209. */
  77210. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  77211. /**
  77212. * Large blur
  77213. */
  77214. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  77215. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  77216. ;
  77217. /**
  77218. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  77219. */
  77220. var DepthOfFieldEffect = /** @class */ (function (_super) {
  77221. __extends(DepthOfFieldEffect, _super);
  77222. /**
  77223. * Creates a new instance DepthOfFieldEffect
  77224. * @param scene The scene the effect belongs to.
  77225. * @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.
  77226. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77227. * @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)
  77228. */
  77229. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  77230. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  77231. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77232. if (blockCompilation === void 0) { blockCompilation = false; }
  77233. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  77234. return _this._effects;
  77235. }, true) || this;
  77236. /**
  77237. * Internal post processes in depth of field effect
  77238. */
  77239. _this._effects = [];
  77240. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  77241. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77242. // 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)
  77243. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  77244. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  77245. _this._depthOfFieldBlurY = [];
  77246. _this._depthOfFieldBlurX = [];
  77247. var blurCount = 1;
  77248. var kernelSize = 15;
  77249. switch (blurLevel) {
  77250. case DepthOfFieldEffectBlurLevel.High: {
  77251. blurCount = 3;
  77252. kernelSize = 51;
  77253. break;
  77254. }
  77255. case DepthOfFieldEffectBlurLevel.Medium: {
  77256. blurCount = 2;
  77257. kernelSize = 31;
  77258. break;
  77259. }
  77260. default: {
  77261. kernelSize = 15;
  77262. blurCount = 1;
  77263. break;
  77264. }
  77265. }
  77266. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  77267. var ratio = 1.0;
  77268. for (var i = 0; i < blurCount; i++) {
  77269. 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);
  77270. blurY.autoClear = false;
  77271. ratio = 0.75 / Math.pow(2, i);
  77272. 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);
  77273. blurX.autoClear = false;
  77274. _this._depthOfFieldBlurY.push(blurY);
  77275. _this._depthOfFieldBlurX.push(blurX);
  77276. }
  77277. // Set all post processes on the effect.
  77278. _this._effects = [_this._circleOfConfusion];
  77279. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  77280. _this._effects.push(_this._depthOfFieldBlurY[i]);
  77281. _this._effects.push(_this._depthOfFieldBlurX[i]);
  77282. }
  77283. // Merge blurred images with original image based on circleOfConfusion
  77284. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77285. _this._dofMerge.autoClear = false;
  77286. _this._effects.push(_this._dofMerge);
  77287. return _this;
  77288. }
  77289. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  77290. get: function () {
  77291. return this._circleOfConfusion.focalLength;
  77292. },
  77293. /**
  77294. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  77295. */
  77296. set: function (value) {
  77297. this._circleOfConfusion.focalLength = value;
  77298. },
  77299. enumerable: true,
  77300. configurable: true
  77301. });
  77302. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  77303. get: function () {
  77304. return this._circleOfConfusion.fStop;
  77305. },
  77306. /**
  77307. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  77308. */
  77309. set: function (value) {
  77310. this._circleOfConfusion.fStop = value;
  77311. },
  77312. enumerable: true,
  77313. configurable: true
  77314. });
  77315. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  77316. get: function () {
  77317. return this._circleOfConfusion.focusDistance;
  77318. },
  77319. /**
  77320. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  77321. */
  77322. set: function (value) {
  77323. this._circleOfConfusion.focusDistance = value;
  77324. },
  77325. enumerable: true,
  77326. configurable: true
  77327. });
  77328. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  77329. get: function () {
  77330. return this._circleOfConfusion.lensSize;
  77331. },
  77332. /**
  77333. * 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.
  77334. */
  77335. set: function (value) {
  77336. this._circleOfConfusion.lensSize = value;
  77337. },
  77338. enumerable: true,
  77339. configurable: true
  77340. });
  77341. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  77342. /**
  77343. * 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.
  77344. */
  77345. set: function (value) {
  77346. this._circleOfConfusion.depthTexture = value;
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. /**
  77352. * Disposes each of the internal effects for a given camera.
  77353. * @param camera The camera to dispose the effect on.
  77354. */
  77355. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  77356. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77357. this._effects[effectIndex].dispose(camera);
  77358. }
  77359. };
  77360. /**
  77361. * Internal
  77362. */
  77363. DepthOfFieldEffect.prototype._updateEffects = function () {
  77364. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77365. this._effects[effectIndex].updateEffect();
  77366. }
  77367. };
  77368. /**
  77369. * Internal
  77370. * @returns if all the contained post processes are ready.
  77371. */
  77372. DepthOfFieldEffect.prototype._isReady = function () {
  77373. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77374. if (!this._effects[effectIndex].isReady()) {
  77375. return false;
  77376. }
  77377. }
  77378. return true;
  77379. };
  77380. return DepthOfFieldEffect;
  77381. }(BABYLON.PostProcessRenderEffect));
  77382. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  77383. })(BABYLON || (BABYLON = {}));
  77384. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  77385. var BABYLON;
  77386. (function (BABYLON) {
  77387. /**
  77388. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  77389. */
  77390. var BloomMergePostProcess = /** @class */ (function (_super) {
  77391. __extends(BloomMergePostProcess, _super);
  77392. /**
  77393. * Creates a new instance of @see BloomMergePostProcess
  77394. * @param name The name of the effect.
  77395. * @param originalFromInput Post process which's input will be used for the merge.
  77396. * @param blurred Blurred highlights post process which's output will be used.
  77397. * @param weight Weight of the bloom to be added to the original input.
  77398. * @param options The required width/height ratio to downsize to before computing the render pass.
  77399. * @param camera The camera to apply the render pass to.
  77400. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77401. * @param engine The engine which the post process will be applied. (default: current engine)
  77402. * @param reusable If the post process can be reused on the same frame. (default: false)
  77403. * @param textureType Type of textures used when performing the post process. (default: 0)
  77404. * @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)
  77405. */
  77406. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77407. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77408. if (blockCompilation === void 0) { blockCompilation = false; }
  77409. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  77410. _this.weight = weight;
  77411. _this.onApplyObservable.add(function (effect) {
  77412. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  77413. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  77414. effect.setFloat("bloomWeight", _this.weight);
  77415. });
  77416. if (!blockCompilation) {
  77417. _this.updateEffect();
  77418. }
  77419. return _this;
  77420. }
  77421. return BloomMergePostProcess;
  77422. }(BABYLON.PostProcess));
  77423. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  77424. })(BABYLON || (BABYLON = {}));
  77425. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  77426. var BABYLON;
  77427. (function (BABYLON) {
  77428. /**
  77429. * 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.
  77430. */
  77431. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  77432. __extends(ExtractHighlightsPostProcess, _super);
  77433. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77434. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77435. if (blockCompilation === void 0) { blockCompilation = false; }
  77436. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77437. /**
  77438. * The luminance threshold, pixels below this value will be set to black.
  77439. */
  77440. _this.threshold = 0.9;
  77441. /**
  77442. * Internal
  77443. */
  77444. _this._exposure = 1;
  77445. /**
  77446. * Post process which has the input texture to be used when performing highlight extraction
  77447. */
  77448. _this._inputPostProcess = null;
  77449. _this.onApplyObservable.add(function (effect) {
  77450. if (_this._inputPostProcess) {
  77451. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  77452. }
  77453. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  77454. effect.setFloat('exposure', _this._exposure);
  77455. });
  77456. return _this;
  77457. }
  77458. return ExtractHighlightsPostProcess;
  77459. }(BABYLON.PostProcess));
  77460. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  77461. })(BABYLON || (BABYLON = {}));
  77462. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  77463. var BABYLON;
  77464. (function (BABYLON) {
  77465. /**
  77466. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  77467. */
  77468. var BloomEffect = /** @class */ (function (_super) {
  77469. __extends(BloomEffect, _super);
  77470. /**
  77471. * Creates a new instance of @see BloomEffect
  77472. * @param scene The scene the effect belongs to.
  77473. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  77474. * @param bloomKernel The size of the kernel to be used when applying the blur.
  77475. * @param bloomWeight The the strength of bloom.
  77476. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  77477. * @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)
  77478. */
  77479. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  77480. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  77481. if (blockCompilation === void 0) { blockCompilation = false; }
  77482. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  77483. return _this._effects;
  77484. }, true) || this;
  77485. _this.bloomScale = bloomScale;
  77486. /**
  77487. * Internal
  77488. */
  77489. _this._effects = [];
  77490. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77491. _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);
  77492. _this._blurX.alwaysForcePOT = true;
  77493. _this._blurX.autoClear = false;
  77494. _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);
  77495. _this._blurY.alwaysForcePOT = true;
  77496. _this._blurY.autoClear = false;
  77497. _this.kernel = bloomKernel;
  77498. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  77499. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  77500. _this._merge.autoClear = false;
  77501. _this._effects.push(_this._merge);
  77502. return _this;
  77503. }
  77504. Object.defineProperty(BloomEffect.prototype, "threshold", {
  77505. /**
  77506. * The luminance threshold to find bright areas of the image to bloom.
  77507. */
  77508. get: function () {
  77509. return this._downscale.threshold;
  77510. },
  77511. set: function (value) {
  77512. this._downscale.threshold = value;
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. Object.defineProperty(BloomEffect.prototype, "weight", {
  77518. /**
  77519. * The strength of the bloom.
  77520. */
  77521. get: function () {
  77522. return this._merge.weight;
  77523. },
  77524. set: function (value) {
  77525. this._merge.weight = value;
  77526. },
  77527. enumerable: true,
  77528. configurable: true
  77529. });
  77530. Object.defineProperty(BloomEffect.prototype, "kernel", {
  77531. /**
  77532. * Specifies the size of the bloom blur kernel, relative to the final output size
  77533. */
  77534. get: function () {
  77535. return this._blurX.kernel / this.bloomScale;
  77536. },
  77537. set: function (value) {
  77538. this._blurX.kernel = value * this.bloomScale;
  77539. this._blurY.kernel = value * this.bloomScale;
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. /**
  77545. * Disposes each of the internal effects for a given camera.
  77546. * @param camera The camera to dispose the effect on.
  77547. */
  77548. BloomEffect.prototype.disposeEffects = function (camera) {
  77549. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77550. this._effects[effectIndex].dispose(camera);
  77551. }
  77552. };
  77553. /**
  77554. * Internal
  77555. */
  77556. BloomEffect.prototype._updateEffects = function () {
  77557. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77558. this._effects[effectIndex].updateEffect();
  77559. }
  77560. };
  77561. /**
  77562. * Internal
  77563. * @returns if all the contained post processes are ready.
  77564. */
  77565. BloomEffect.prototype._isReady = function () {
  77566. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  77567. if (!this._effects[effectIndex].isReady()) {
  77568. return false;
  77569. }
  77570. }
  77571. return true;
  77572. };
  77573. return BloomEffect;
  77574. }(BABYLON.PostProcessRenderEffect));
  77575. BABYLON.BloomEffect = BloomEffect;
  77576. })(BABYLON || (BABYLON = {}));
  77577. //# sourceMappingURL=babylon.bloomEffect.js.map
  77578. var BABYLON;
  77579. (function (BABYLON) {
  77580. /**
  77581. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  77582. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  77583. */
  77584. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  77585. __extends(DefaultRenderingPipeline, _super);
  77586. /**
  77587. * @constructor
  77588. * @param {string} name - The rendering pipeline name (default: "")
  77589. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  77590. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  77591. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  77592. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  77593. */
  77594. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  77595. if (name === void 0) { name = ""; }
  77596. if (hdr === void 0) { hdr = true; }
  77597. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  77598. if (automaticBuild === void 0) { automaticBuild = true; }
  77599. var _this = _super.call(this, scene.getEngine(), name) || this;
  77600. _this._camerasToBeAttached = [];
  77601. /**
  77602. * ID of the sharpen post process,
  77603. */
  77604. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  77605. /**
  77606. * ID of the image processing post process;
  77607. */
  77608. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  77609. /**
  77610. * ID of the Fast Approximate Anti-Aliasing post process;
  77611. */
  77612. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  77613. /**
  77614. * ID of the chromatic aberration post process,
  77615. */
  77616. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  77617. /**
  77618. * ID of the grain post process
  77619. */
  77620. _this.GrainPostProcessId = "GrainPostProcessEffect";
  77621. /**
  77622. * Glow post process which adds a glow to emmisive areas of the image
  77623. */
  77624. _this._glowLayer = null;
  77625. /**
  77626. * Animations which can be used to tweak settings over a period of time
  77627. */
  77628. _this.animations = [];
  77629. _this._imageProcessingConfigurationObserver = null;
  77630. // Values
  77631. _this._sharpenEnabled = false;
  77632. _this._bloomEnabled = false;
  77633. _this._depthOfFieldEnabled = false;
  77634. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  77635. _this._fxaaEnabled = false;
  77636. _this._imageProcessingEnabled = true;
  77637. _this._bloomScale = 0.5;
  77638. _this._chromaticAberrationEnabled = false;
  77639. _this._grainEnabled = false;
  77640. _this._buildAllowed = true;
  77641. _this._resizeObserver = null;
  77642. _this._hardwareScaleLevel = 1.0;
  77643. _this._bloomKernel = 64;
  77644. /**
  77645. * Specifies the weight of the bloom in the final rendering
  77646. */
  77647. _this._bloomWeight = 0.15;
  77648. /**
  77649. * Specifies the luma threshold for the area that will be blurred by the bloom
  77650. */
  77651. _this._bloomThreshold = 0.9;
  77652. _this._samples = 1;
  77653. _this._hasCleared = false;
  77654. _this._prevPostProcess = null;
  77655. _this._prevPrevPostProcess = null;
  77656. _this._cameras = cameras || scene.cameras;
  77657. _this._camerasToBeAttached = _this._cameras.slice();
  77658. _this._buildAllowed = automaticBuild;
  77659. // Initialize
  77660. _this._scene = scene;
  77661. var caps = _this._scene.getEngine().getCaps();
  77662. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  77663. // Misc
  77664. if (_this._hdr) {
  77665. if (caps.textureHalfFloatRender) {
  77666. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77667. }
  77668. else if (caps.textureFloatRender) {
  77669. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77670. }
  77671. }
  77672. else {
  77673. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77674. }
  77675. // Attach
  77676. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77677. var engine = _this._scene.getEngine();
  77678. // Create post processes before hand so they can be modified before enabled.
  77679. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  77680. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77681. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  77682. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  77683. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  77684. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77685. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  77686. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  77687. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  77688. _this._resizeObserver = engine.onResizeObservable.add(function () {
  77689. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  77690. _this.bloomKernel = _this.bloomKernel;
  77691. });
  77692. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  77693. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  77694. });
  77695. _this._buildPipeline();
  77696. return _this;
  77697. }
  77698. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  77699. get: function () {
  77700. return this._sharpenEnabled;
  77701. },
  77702. /**
  77703. * Enable or disable the sharpen process from the pipeline
  77704. */
  77705. set: function (enabled) {
  77706. if (this._sharpenEnabled === enabled) {
  77707. return;
  77708. }
  77709. this._sharpenEnabled = enabled;
  77710. this._buildPipeline();
  77711. },
  77712. enumerable: true,
  77713. configurable: true
  77714. });
  77715. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  77716. /**
  77717. * Specifies the size of the bloom blur kernel, relative to the final output size
  77718. */
  77719. get: function () {
  77720. return this._bloomKernel;
  77721. },
  77722. set: function (value) {
  77723. this._bloomKernel = value;
  77724. this.bloom.kernel = value / this._hardwareScaleLevel;
  77725. },
  77726. enumerable: true,
  77727. configurable: true
  77728. });
  77729. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  77730. get: function () {
  77731. return this._bloomWeight;
  77732. },
  77733. /**
  77734. * The strength of the bloom.
  77735. */
  77736. set: function (value) {
  77737. if (this._bloomWeight === value) {
  77738. return;
  77739. }
  77740. this.bloom.weight = value;
  77741. this._bloomWeight = value;
  77742. },
  77743. enumerable: true,
  77744. configurable: true
  77745. });
  77746. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  77747. get: function () {
  77748. return this._bloomThreshold;
  77749. },
  77750. /**
  77751. * The strength of the bloom.
  77752. */
  77753. set: function (value) {
  77754. if (this._bloomThreshold === value) {
  77755. return;
  77756. }
  77757. this.bloom.threshold = value;
  77758. this._bloomThreshold = value;
  77759. },
  77760. enumerable: true,
  77761. configurable: true
  77762. });
  77763. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  77764. get: function () {
  77765. return this._bloomScale;
  77766. },
  77767. /**
  77768. * The scale of the bloom, lower value will provide better performance.
  77769. */
  77770. set: function (value) {
  77771. if (this._bloomScale === value) {
  77772. return;
  77773. }
  77774. this._bloomScale = value;
  77775. // recreate bloom and dispose old as this setting is not dynamic
  77776. this._rebuildBloom();
  77777. this._buildPipeline();
  77778. },
  77779. enumerable: true,
  77780. configurable: true
  77781. });
  77782. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  77783. get: function () {
  77784. return this._bloomEnabled;
  77785. },
  77786. /**
  77787. * Enable or disable the bloom from the pipeline
  77788. */
  77789. set: function (enabled) {
  77790. if (this._bloomEnabled === enabled) {
  77791. return;
  77792. }
  77793. this._bloomEnabled = enabled;
  77794. this._buildPipeline();
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  77800. // recreate bloom and dispose old as this setting is not dynamic
  77801. var oldBloom = this.bloom;
  77802. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  77803. this.bloom.threshold = oldBloom.threshold;
  77804. for (var i = 0; i < this._cameras.length; i++) {
  77805. oldBloom.disposeEffects(this._cameras[i]);
  77806. }
  77807. };
  77808. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  77809. /**
  77810. * If the depth of field is enabled.
  77811. */
  77812. get: function () {
  77813. return this._depthOfFieldEnabled;
  77814. },
  77815. set: function (enabled) {
  77816. if (this._depthOfFieldEnabled === enabled) {
  77817. return;
  77818. }
  77819. this._depthOfFieldEnabled = enabled;
  77820. this._buildPipeline();
  77821. },
  77822. enumerable: true,
  77823. configurable: true
  77824. });
  77825. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  77826. /**
  77827. * Blur level of the depth of field effect. (Higher blur will effect performance)
  77828. */
  77829. get: function () {
  77830. return this._depthOfFieldBlurLevel;
  77831. },
  77832. set: function (value) {
  77833. if (this._depthOfFieldBlurLevel === value) {
  77834. return;
  77835. }
  77836. this._depthOfFieldBlurLevel = value;
  77837. // recreate dof and dispose old as this setting is not dynamic
  77838. var oldDof = this.depthOfField;
  77839. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  77840. this.depthOfField.focalLength = oldDof.focalLength;
  77841. this.depthOfField.focusDistance = oldDof.focusDistance;
  77842. this.depthOfField.fStop = oldDof.fStop;
  77843. this.depthOfField.lensSize = oldDof.lensSize;
  77844. for (var i = 0; i < this._cameras.length; i++) {
  77845. oldDof.disposeEffects(this._cameras[i]);
  77846. }
  77847. this._buildPipeline();
  77848. },
  77849. enumerable: true,
  77850. configurable: true
  77851. });
  77852. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  77853. get: function () {
  77854. return this._fxaaEnabled;
  77855. },
  77856. /**
  77857. * If the anti aliasing is enabled.
  77858. */
  77859. set: function (enabled) {
  77860. if (this._fxaaEnabled === enabled) {
  77861. return;
  77862. }
  77863. this._fxaaEnabled = enabled;
  77864. this._buildPipeline();
  77865. },
  77866. enumerable: true,
  77867. configurable: true
  77868. });
  77869. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  77870. get: function () {
  77871. return this._samples;
  77872. },
  77873. /**
  77874. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  77875. */
  77876. set: function (sampleCount) {
  77877. if (this._samples === sampleCount) {
  77878. return;
  77879. }
  77880. this._samples = sampleCount;
  77881. this._buildPipeline();
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  77887. get: function () {
  77888. return this._imageProcessingEnabled;
  77889. },
  77890. /**
  77891. * If image processing is enabled.
  77892. */
  77893. set: function (enabled) {
  77894. if (this._imageProcessingEnabled === enabled) {
  77895. return;
  77896. }
  77897. this._imageProcessingEnabled = enabled;
  77898. this._buildPipeline();
  77899. },
  77900. enumerable: true,
  77901. configurable: true
  77902. });
  77903. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  77904. get: function () {
  77905. return this._glowLayer == null;
  77906. },
  77907. /**
  77908. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  77909. */
  77910. set: function (enabled) {
  77911. if (enabled && !this._glowLayer) {
  77912. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  77913. }
  77914. else if (!enabled && this._glowLayer) {
  77915. this._glowLayer.dispose();
  77916. this._glowLayer = null;
  77917. }
  77918. },
  77919. enumerable: true,
  77920. configurable: true
  77921. });
  77922. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  77923. get: function () {
  77924. return this._chromaticAberrationEnabled;
  77925. },
  77926. /**
  77927. * Enable or disable the chromaticAberration process from the pipeline
  77928. */
  77929. set: function (enabled) {
  77930. if (this._chromaticAberrationEnabled === enabled) {
  77931. return;
  77932. }
  77933. this._chromaticAberrationEnabled = enabled;
  77934. this._buildPipeline();
  77935. },
  77936. enumerable: true,
  77937. configurable: true
  77938. });
  77939. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  77940. get: function () {
  77941. return this._grainEnabled;
  77942. },
  77943. /**
  77944. * Enable or disable the grain process from the pipeline
  77945. */
  77946. set: function (enabled) {
  77947. if (this._grainEnabled === enabled) {
  77948. return;
  77949. }
  77950. this._grainEnabled = enabled;
  77951. this._buildPipeline();
  77952. },
  77953. enumerable: true,
  77954. configurable: true
  77955. });
  77956. /**
  77957. * Force the compilation of the entire pipeline.
  77958. */
  77959. DefaultRenderingPipeline.prototype.prepare = function () {
  77960. var previousState = this._buildAllowed;
  77961. this._buildAllowed = true;
  77962. this._buildPipeline();
  77963. this._buildAllowed = previousState;
  77964. };
  77965. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  77966. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  77967. if (this._hasCleared) {
  77968. postProcess.autoClear = false;
  77969. }
  77970. else {
  77971. postProcess.autoClear = true;
  77972. this._scene.autoClear = false;
  77973. this._hasCleared = true;
  77974. }
  77975. if (!skipTextureSharing) {
  77976. if (this._prevPrevPostProcess) {
  77977. postProcess.shareOutputWith(this._prevPrevPostProcess);
  77978. }
  77979. else {
  77980. postProcess.useOwnOutput();
  77981. }
  77982. if (this._prevPostProcess) {
  77983. this._prevPrevPostProcess = this._prevPostProcess;
  77984. }
  77985. this._prevPostProcess = postProcess;
  77986. }
  77987. };
  77988. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  77989. var _this = this;
  77990. if (!this._buildAllowed) {
  77991. return;
  77992. }
  77993. this._scene.autoClear = true;
  77994. var engine = this._scene.getEngine();
  77995. this._disposePostProcesses();
  77996. if (this._cameras !== null) {
  77997. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77998. // get back cameras to be used to reattach pipeline
  77999. this._cameras = this._camerasToBeAttached.slice();
  78000. }
  78001. this._reset();
  78002. this._prevPostProcess = null;
  78003. this._prevPrevPostProcess = null;
  78004. this._hasCleared = false;
  78005. if (this.depthOfFieldEnabled) {
  78006. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  78007. this.depthOfField.depthTexture = depthTexture;
  78008. if (!this.depthOfField._isReady()) {
  78009. this.depthOfField._updateEffects();
  78010. }
  78011. this.addEffect(this.depthOfField);
  78012. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  78013. }
  78014. if (this.bloomEnabled) {
  78015. if (!this.bloom._isReady()) {
  78016. this.bloom._updateEffects();
  78017. }
  78018. this.addEffect(this.bloom);
  78019. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  78020. }
  78021. if (this._imageProcessingEnabled) {
  78022. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78023. if (this._hdr) {
  78024. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  78025. this._setAutoClearAndTextureSharing(this.imageProcessing);
  78026. }
  78027. else {
  78028. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  78029. }
  78030. }
  78031. if (this.sharpenEnabled) {
  78032. if (!this.sharpen.isReady()) {
  78033. this.sharpen.updateEffect();
  78034. }
  78035. this.addEffect(this._sharpenEffect);
  78036. this._setAutoClearAndTextureSharing(this.sharpen);
  78037. }
  78038. if (this.grainEnabled) {
  78039. if (!this.grain.isReady()) {
  78040. this.grain.updateEffect();
  78041. }
  78042. this.addEffect(this._grainEffect);
  78043. this._setAutoClearAndTextureSharing(this.grain);
  78044. }
  78045. if (this.chromaticAberrationEnabled) {
  78046. if (!this.chromaticAberration.isReady()) {
  78047. this.chromaticAberration.updateEffect();
  78048. }
  78049. this.addEffect(this._chromaticAberrationEffect);
  78050. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  78051. }
  78052. if (this.fxaaEnabled) {
  78053. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  78054. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  78055. this._setAutoClearAndTextureSharing(this.fxaa, true);
  78056. }
  78057. if (this._cameras !== null) {
  78058. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  78059. }
  78060. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  78061. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  78062. }
  78063. };
  78064. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  78065. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  78066. for (var i = 0; i < this._cameras.length; i++) {
  78067. var camera = this._cameras[i];
  78068. if (this.imageProcessing) {
  78069. this.imageProcessing.dispose(camera);
  78070. }
  78071. if (this.fxaa) {
  78072. this.fxaa.dispose(camera);
  78073. }
  78074. // These are created in the constructor and should not be disposed on every pipeline change
  78075. if (disposeNonRecreated) {
  78076. if (this.sharpen) {
  78077. this.sharpen.dispose(camera);
  78078. }
  78079. if (this.depthOfField) {
  78080. this.depthOfField.disposeEffects(camera);
  78081. }
  78082. if (this.bloom) {
  78083. this.bloom.disposeEffects(camera);
  78084. }
  78085. if (this.chromaticAberration) {
  78086. this.chromaticAberration.dispose(camera);
  78087. }
  78088. if (this.grain) {
  78089. this.grain.dispose(camera);
  78090. }
  78091. if (this._glowLayer) {
  78092. this._glowLayer.dispose();
  78093. }
  78094. }
  78095. }
  78096. this.imageProcessing = null;
  78097. this.fxaa = null;
  78098. if (disposeNonRecreated) {
  78099. this.sharpen = null;
  78100. this._sharpenEffect = null;
  78101. this.depthOfField = null;
  78102. this.bloom = null;
  78103. this.chromaticAberration = null;
  78104. this._chromaticAberrationEffect = null;
  78105. this.grain = null;
  78106. this._grainEffect = null;
  78107. this._glowLayer = null;
  78108. }
  78109. };
  78110. /**
  78111. * Adds a camera to the pipeline
  78112. * @param camera the camera to be added
  78113. */
  78114. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  78115. this._camerasToBeAttached.push(camera);
  78116. this._buildPipeline();
  78117. };
  78118. /**
  78119. * Removes a camera from the pipeline
  78120. * @param camera the camera to remove
  78121. */
  78122. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  78123. var index = this._camerasToBeAttached.indexOf(camera);
  78124. this._camerasToBeAttached.splice(index, 1);
  78125. this._buildPipeline();
  78126. };
  78127. /**
  78128. * Dispose of the pipeline and stop all post processes
  78129. */
  78130. DefaultRenderingPipeline.prototype.dispose = function () {
  78131. this._disposePostProcesses(true);
  78132. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  78133. this._scene.autoClear = true;
  78134. if (this._resizeObserver) {
  78135. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  78136. this._resizeObserver = null;
  78137. }
  78138. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  78139. _super.prototype.dispose.call(this);
  78140. };
  78141. /**
  78142. * Serialize the rendering pipeline (Used when exporting)
  78143. * @returns the serialized object
  78144. */
  78145. DefaultRenderingPipeline.prototype.serialize = function () {
  78146. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  78147. serializationObject.customType = "DefaultRenderingPipeline";
  78148. return serializationObject;
  78149. };
  78150. /**
  78151. * Parse the serialized pipeline
  78152. * @param source Source pipeline.
  78153. * @param scene The scene to load the pipeline to.
  78154. * @param rootUrl The URL of the serialized pipeline.
  78155. * @returns An instantiated pipeline from the serialized object.
  78156. */
  78157. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  78158. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  78159. };
  78160. __decorate([
  78161. BABYLON.serialize()
  78162. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  78163. __decorate([
  78164. BABYLON.serialize()
  78165. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  78166. __decorate([
  78167. BABYLON.serialize()
  78168. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  78169. __decorate([
  78170. BABYLON.serialize()
  78171. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  78172. __decorate([
  78173. BABYLON.serialize()
  78174. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  78175. __decorate([
  78176. BABYLON.serialize()
  78177. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  78178. __decorate([
  78179. BABYLON.serialize()
  78180. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  78181. __decorate([
  78182. BABYLON.serialize()
  78183. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  78184. __decorate([
  78185. BABYLON.serialize()
  78186. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  78187. __decorate([
  78188. BABYLON.serialize()
  78189. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  78190. __decorate([
  78191. BABYLON.serialize()
  78192. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  78193. __decorate([
  78194. BABYLON.serialize()
  78195. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  78196. __decorate([
  78197. BABYLON.serialize()
  78198. ], DefaultRenderingPipeline.prototype, "samples", null);
  78199. __decorate([
  78200. BABYLON.serialize()
  78201. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  78202. __decorate([
  78203. BABYLON.serialize()
  78204. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  78205. __decorate([
  78206. BABYLON.serialize()
  78207. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  78208. __decorate([
  78209. BABYLON.serialize()
  78210. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  78211. return DefaultRenderingPipeline;
  78212. }(BABYLON.PostProcessRenderPipeline));
  78213. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  78214. })(BABYLON || (BABYLON = {}));
  78215. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  78216. var BABYLON;
  78217. (function (BABYLON) {
  78218. /**
  78219. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  78220. */
  78221. var GeometryBufferRenderer = /** @class */ (function () {
  78222. /**
  78223. * Creates a new G Buffer for the scene
  78224. * @param scene The scene the buffer belongs to
  78225. * @param ratio How big is the buffer related to the main canvas.
  78226. */
  78227. function GeometryBufferRenderer(scene, ratio) {
  78228. if (ratio === void 0) { ratio = 1; }
  78229. this._enablePosition = false;
  78230. this._scene = scene;
  78231. this._ratio = ratio;
  78232. // Render target
  78233. this._createRenderTargets();
  78234. }
  78235. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  78236. /**
  78237. * Set the render list (meshes to be rendered) used in the G buffer.
  78238. */
  78239. set: function (meshes) {
  78240. this._multiRenderTarget.renderList = meshes;
  78241. },
  78242. enumerable: true,
  78243. configurable: true
  78244. });
  78245. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  78246. /**
  78247. * Gets wether or not G buffer are supported by the running hardware.
  78248. * This requires draw buffer supports
  78249. */
  78250. get: function () {
  78251. return this._multiRenderTarget.isSupported;
  78252. },
  78253. enumerable: true,
  78254. configurable: true
  78255. });
  78256. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  78257. /**
  78258. * Gets wether or not position are enabled for the G buffer.
  78259. */
  78260. get: function () {
  78261. return this._enablePosition;
  78262. },
  78263. /**
  78264. * Sets wether or not position are enabled for the G buffer.
  78265. */
  78266. set: function (enable) {
  78267. this._enablePosition = enable;
  78268. this.dispose();
  78269. this._createRenderTargets();
  78270. },
  78271. enumerable: true,
  78272. configurable: true
  78273. });
  78274. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  78275. /**
  78276. * Gets the scene associated with the buffer.
  78277. */
  78278. get: function () {
  78279. return this._scene;
  78280. },
  78281. enumerable: true,
  78282. configurable: true
  78283. });
  78284. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  78285. /**
  78286. * Gets the ratio used by the buffer during its creation.
  78287. * How big is the buffer related to the main canvas.
  78288. */
  78289. get: function () {
  78290. return this._ratio;
  78291. },
  78292. enumerable: true,
  78293. configurable: true
  78294. });
  78295. /**
  78296. * Checks wether everything is ready to render a submesh to the G buffer.
  78297. * @param subMesh the submesh to check readiness for
  78298. * @param useInstances is the mesh drawn using instance or not
  78299. * @returns true if ready otherwise false
  78300. */
  78301. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  78302. var material = subMesh.getMaterial();
  78303. if (material && material.disableDepthWrite) {
  78304. return false;
  78305. }
  78306. var defines = [];
  78307. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78308. var mesh = subMesh.getMesh();
  78309. // Alpha test
  78310. if (material && material.needAlphaTesting()) {
  78311. defines.push("#define ALPHATEST");
  78312. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78313. attribs.push(BABYLON.VertexBuffer.UVKind);
  78314. defines.push("#define UV1");
  78315. }
  78316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78317. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78318. defines.push("#define UV2");
  78319. }
  78320. }
  78321. // Buffers
  78322. if (this._enablePosition) {
  78323. defines.push("#define POSITION");
  78324. }
  78325. // Bones
  78326. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78329. if (mesh.numBoneInfluencers > 4) {
  78330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78332. }
  78333. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78334. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78335. }
  78336. else {
  78337. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78338. }
  78339. // Instances
  78340. if (useInstances) {
  78341. defines.push("#define INSTANCES");
  78342. attribs.push("world0");
  78343. attribs.push("world1");
  78344. attribs.push("world2");
  78345. attribs.push("world3");
  78346. }
  78347. // Get correct effect
  78348. var join = defines.join("\n");
  78349. if (this._cachedDefines !== join) {
  78350. this._cachedDefines = join;
  78351. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  78352. }
  78353. return this._effect.isReady();
  78354. };
  78355. /**
  78356. * Gets the current underlying G Buffer.
  78357. * @returns the buffer
  78358. */
  78359. GeometryBufferRenderer.prototype.getGBuffer = function () {
  78360. return this._multiRenderTarget;
  78361. };
  78362. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  78363. /**
  78364. * Gets the number of samples used to render the buffer (anti aliasing).
  78365. */
  78366. get: function () {
  78367. return this._multiRenderTarget.samples;
  78368. },
  78369. /**
  78370. * Sets the number of samples used to render the buffer (anti aliasing).
  78371. */
  78372. set: function (value) {
  78373. this._multiRenderTarget.samples = value;
  78374. },
  78375. enumerable: true,
  78376. configurable: true
  78377. });
  78378. /**
  78379. * Disposes the renderer and frees up associated resources.
  78380. */
  78381. GeometryBufferRenderer.prototype.dispose = function () {
  78382. this.getGBuffer().dispose();
  78383. };
  78384. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  78385. var _this = this;
  78386. var engine = this._scene.getEngine();
  78387. var count = this._enablePosition ? 3 : 2;
  78388. 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 });
  78389. if (!this.isSupported) {
  78390. return;
  78391. }
  78392. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78393. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78394. this._multiRenderTarget.refreshRate = 1;
  78395. this._multiRenderTarget.renderParticles = false;
  78396. this._multiRenderTarget.renderList = null;
  78397. // set default depth value to 1.0 (far away)
  78398. this._multiRenderTarget.onClearObservable.add(function (engine) {
  78399. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  78400. });
  78401. // Custom render function
  78402. var renderSubMesh = function (subMesh) {
  78403. var mesh = subMesh.getRenderingMesh();
  78404. var scene = _this._scene;
  78405. var engine = scene.getEngine();
  78406. var material = subMesh.getMaterial();
  78407. if (!material) {
  78408. return;
  78409. }
  78410. // Culling
  78411. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  78412. // Managing instances
  78413. var batch = mesh._getInstancesRenderList(subMesh._id);
  78414. if (batch.mustReturn) {
  78415. return;
  78416. }
  78417. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78418. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  78419. engine.enableEffect(_this._effect);
  78420. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  78421. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78422. _this._effect.setMatrix("view", scene.getViewMatrix());
  78423. // Alpha test
  78424. if (material && material.needAlphaTesting()) {
  78425. var alphaTexture = material.getAlphaTestTexture();
  78426. if (alphaTexture) {
  78427. _this._effect.setTexture("diffuseSampler", alphaTexture);
  78428. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78429. }
  78430. }
  78431. // Bones
  78432. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78433. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78434. }
  78435. // Draw
  78436. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  78437. }
  78438. };
  78439. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78440. var index;
  78441. if (depthOnlySubMeshes.length) {
  78442. engine.setColorWrite(false);
  78443. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78444. renderSubMesh(depthOnlySubMeshes.data[index]);
  78445. }
  78446. engine.setColorWrite(true);
  78447. }
  78448. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78449. renderSubMesh(opaqueSubMeshes.data[index]);
  78450. }
  78451. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78452. renderSubMesh(alphaTestSubMeshes.data[index]);
  78453. }
  78454. };
  78455. };
  78456. return GeometryBufferRenderer;
  78457. }());
  78458. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  78459. })(BABYLON || (BABYLON = {}));
  78460. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  78461. var BABYLON;
  78462. (function (BABYLON) {
  78463. /**
  78464. * This groups together the common properties used for image processing either in direct forward pass
  78465. * or through post processing effect depending on the use of the image processing pipeline in your scene
  78466. * or not.
  78467. */
  78468. var ImageProcessingConfiguration = /** @class */ (function () {
  78469. function ImageProcessingConfiguration() {
  78470. /**
  78471. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  78472. */
  78473. this.colorCurves = new BABYLON.ColorCurves();
  78474. this._colorCurvesEnabled = false;
  78475. this._colorGradingEnabled = false;
  78476. this._colorGradingWithGreenDepth = true;
  78477. this._colorGradingBGR = true;
  78478. this._exposure = 1.0;
  78479. this._toneMappingEnabled = false;
  78480. this._contrast = 1.0;
  78481. /**
  78482. * Vignette stretch size.
  78483. */
  78484. this.vignetteStretch = 0;
  78485. /**
  78486. * Vignette centre X Offset.
  78487. */
  78488. this.vignetteCentreX = 0;
  78489. /**
  78490. * Vignette centre Y Offset.
  78491. */
  78492. this.vignetteCentreY = 0;
  78493. /**
  78494. * Vignette weight or intensity of the vignette effect.
  78495. */
  78496. this.vignetteWeight = 1.5;
  78497. /**
  78498. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78499. * if vignetteEnabled is set to true.
  78500. */
  78501. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  78502. /**
  78503. * Camera field of view used by the Vignette effect.
  78504. */
  78505. this.vignetteCameraFov = 0.5;
  78506. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  78507. this._vignetteEnabled = false;
  78508. this._applyByPostProcess = false;
  78509. this._isEnabled = true;
  78510. /**
  78511. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  78512. */
  78513. this.onUpdateParameters = new BABYLON.Observable();
  78514. }
  78515. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  78516. /**
  78517. * Gets wether the color curves effect is enabled.
  78518. */
  78519. get: function () {
  78520. return this._colorCurvesEnabled;
  78521. },
  78522. /**
  78523. * Sets wether the color curves effect is enabled.
  78524. */
  78525. set: function (value) {
  78526. if (this._colorCurvesEnabled === value) {
  78527. return;
  78528. }
  78529. this._colorCurvesEnabled = value;
  78530. this._updateParameters();
  78531. },
  78532. enumerable: true,
  78533. configurable: true
  78534. });
  78535. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  78536. /**
  78537. * Gets wether the color grading effect is enabled.
  78538. */
  78539. get: function () {
  78540. return this._colorGradingEnabled;
  78541. },
  78542. /**
  78543. * Sets wether the color grading effect is enabled.
  78544. */
  78545. set: function (value) {
  78546. if (this._colorGradingEnabled === value) {
  78547. return;
  78548. }
  78549. this._colorGradingEnabled = value;
  78550. this._updateParameters();
  78551. },
  78552. enumerable: true,
  78553. configurable: true
  78554. });
  78555. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  78556. /**
  78557. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  78558. */
  78559. get: function () {
  78560. return this._colorGradingWithGreenDepth;
  78561. },
  78562. /**
  78563. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  78564. */
  78565. set: function (value) {
  78566. if (this._colorGradingWithGreenDepth === value) {
  78567. return;
  78568. }
  78569. this._colorGradingWithGreenDepth = value;
  78570. this._updateParameters();
  78571. },
  78572. enumerable: true,
  78573. configurable: true
  78574. });
  78575. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  78576. /**
  78577. * Gets wether the color grading texture contains BGR values.
  78578. */
  78579. get: function () {
  78580. return this._colorGradingBGR;
  78581. },
  78582. /**
  78583. * Sets wether the color grading texture contains BGR values.
  78584. */
  78585. set: function (value) {
  78586. if (this._colorGradingBGR === value) {
  78587. return;
  78588. }
  78589. this._colorGradingBGR = value;
  78590. this._updateParameters();
  78591. },
  78592. enumerable: true,
  78593. configurable: true
  78594. });
  78595. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  78596. /**
  78597. * Gets the Exposure used in the effect.
  78598. */
  78599. get: function () {
  78600. return this._exposure;
  78601. },
  78602. /**
  78603. * Sets the Exposure used in the effect.
  78604. */
  78605. set: function (value) {
  78606. if (this._exposure === value) {
  78607. return;
  78608. }
  78609. this._exposure = value;
  78610. this._updateParameters();
  78611. },
  78612. enumerable: true,
  78613. configurable: true
  78614. });
  78615. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  78616. /**
  78617. * Gets wether the tone mapping effect is enabled.
  78618. */
  78619. get: function () {
  78620. return this._toneMappingEnabled;
  78621. },
  78622. /**
  78623. * Sets wether the tone mapping effect is enabled.
  78624. */
  78625. set: function (value) {
  78626. if (this._toneMappingEnabled === value) {
  78627. return;
  78628. }
  78629. this._toneMappingEnabled = value;
  78630. this._updateParameters();
  78631. },
  78632. enumerable: true,
  78633. configurable: true
  78634. });
  78635. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  78636. /**
  78637. * Gets the contrast used in the effect.
  78638. */
  78639. get: function () {
  78640. return this._contrast;
  78641. },
  78642. /**
  78643. * Sets the contrast used in the effect.
  78644. */
  78645. set: function (value) {
  78646. if (this._contrast === value) {
  78647. return;
  78648. }
  78649. this._contrast = value;
  78650. this._updateParameters();
  78651. },
  78652. enumerable: true,
  78653. configurable: true
  78654. });
  78655. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  78656. /**
  78657. * Gets the vignette blend mode allowing different kind of effect.
  78658. */
  78659. get: function () {
  78660. return this._vignetteBlendMode;
  78661. },
  78662. /**
  78663. * Sets the vignette blend mode allowing different kind of effect.
  78664. */
  78665. set: function (value) {
  78666. if (this._vignetteBlendMode === value) {
  78667. return;
  78668. }
  78669. this._vignetteBlendMode = value;
  78670. this._updateParameters();
  78671. },
  78672. enumerable: true,
  78673. configurable: true
  78674. });
  78675. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  78676. /**
  78677. * Gets wether the vignette effect is enabled.
  78678. */
  78679. get: function () {
  78680. return this._vignetteEnabled;
  78681. },
  78682. /**
  78683. * Sets wether the vignette effect is enabled.
  78684. */
  78685. set: function (value) {
  78686. if (this._vignetteEnabled === value) {
  78687. return;
  78688. }
  78689. this._vignetteEnabled = value;
  78690. this._updateParameters();
  78691. },
  78692. enumerable: true,
  78693. configurable: true
  78694. });
  78695. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  78696. /**
  78697. * Gets wether the image processing is applied through a post process or not.
  78698. */
  78699. get: function () {
  78700. return this._applyByPostProcess;
  78701. },
  78702. /**
  78703. * Sets wether the image processing is applied through a post process or not.
  78704. */
  78705. set: function (value) {
  78706. if (this._applyByPostProcess === value) {
  78707. return;
  78708. }
  78709. this._applyByPostProcess = value;
  78710. this._updateParameters();
  78711. },
  78712. enumerable: true,
  78713. configurable: true
  78714. });
  78715. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  78716. /**
  78717. * Gets wether the image processing is enabled or not.
  78718. */
  78719. get: function () {
  78720. return this._isEnabled;
  78721. },
  78722. /**
  78723. * Sets wether the image processing is enabled or not.
  78724. */
  78725. set: function (value) {
  78726. if (this._isEnabled === value) {
  78727. return;
  78728. }
  78729. this._isEnabled = value;
  78730. this._updateParameters();
  78731. },
  78732. enumerable: true,
  78733. configurable: true
  78734. });
  78735. /**
  78736. * Method called each time the image processing information changes requires to recompile the effect.
  78737. */
  78738. ImageProcessingConfiguration.prototype._updateParameters = function () {
  78739. this.onUpdateParameters.notifyObservers(this);
  78740. };
  78741. ImageProcessingConfiguration.prototype.getClassName = function () {
  78742. return "ImageProcessingConfiguration";
  78743. };
  78744. /**
  78745. * Prepare the list of uniforms associated with the Image Processing effects.
  78746. * @param uniformsList The list of uniforms used in the effect
  78747. * @param defines the list of defines currently in use
  78748. */
  78749. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  78750. if (defines.EXPOSURE) {
  78751. uniforms.push("exposureLinear");
  78752. }
  78753. if (defines.CONTRAST) {
  78754. uniforms.push("contrast");
  78755. }
  78756. if (defines.COLORGRADING) {
  78757. uniforms.push("colorTransformSettings");
  78758. }
  78759. if (defines.VIGNETTE) {
  78760. uniforms.push("vInverseScreenSize");
  78761. uniforms.push("vignetteSettings1");
  78762. uniforms.push("vignetteSettings2");
  78763. }
  78764. if (defines.COLORCURVES) {
  78765. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  78766. }
  78767. };
  78768. /**
  78769. * Prepare the list of samplers associated with the Image Processing effects.
  78770. * @param uniformsList The list of uniforms used in the effect
  78771. * @param defines the list of defines currently in use
  78772. */
  78773. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  78774. if (defines.COLORGRADING) {
  78775. samplersList.push("txColorTransform");
  78776. }
  78777. };
  78778. /**
  78779. * Prepare the list of defines associated to the shader.
  78780. * @param defines the list of defines to complete
  78781. */
  78782. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  78783. if (forPostProcess === void 0) { forPostProcess = false; }
  78784. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  78785. defines.VIGNETTE = false;
  78786. defines.TONEMAPPING = false;
  78787. defines.CONTRAST = false;
  78788. defines.EXPOSURE = false;
  78789. defines.COLORCURVES = false;
  78790. defines.COLORGRADING = false;
  78791. defines.COLORGRADING3D = false;
  78792. defines.IMAGEPROCESSING = false;
  78793. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  78794. return;
  78795. }
  78796. defines.VIGNETTE = this.vignetteEnabled;
  78797. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  78798. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  78799. defines.TONEMAPPING = this.toneMappingEnabled;
  78800. defines.CONTRAST = (this.contrast !== 1.0);
  78801. defines.EXPOSURE = (this.exposure !== 1.0);
  78802. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  78803. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  78804. if (defines.COLORGRADING) {
  78805. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  78806. }
  78807. else {
  78808. defines.COLORGRADING3D = false;
  78809. }
  78810. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  78811. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  78812. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  78813. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  78814. };
  78815. /**
  78816. * Returns true if all the image processing information are ready.
  78817. */
  78818. ImageProcessingConfiguration.prototype.isReady = function () {
  78819. // Color Grading texure can not be none blocking.
  78820. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  78821. };
  78822. /**
  78823. * Binds the image processing to the shader.
  78824. * @param effect The effect to bind to
  78825. */
  78826. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  78827. if (aspectRatio === void 0) { aspectRatio = 1; }
  78828. // Color Curves
  78829. if (this._colorCurvesEnabled && this.colorCurves) {
  78830. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  78831. }
  78832. // Vignette
  78833. if (this._vignetteEnabled) {
  78834. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  78835. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  78836. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  78837. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  78838. var vignetteScaleX = vignetteScaleY * aspectRatio;
  78839. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  78840. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  78841. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  78842. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  78843. var vignettePower = -2.0 * this.vignetteWeight;
  78844. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  78845. }
  78846. // Exposure
  78847. effect.setFloat("exposureLinear", this.exposure);
  78848. // Contrast
  78849. effect.setFloat("contrast", this.contrast);
  78850. // Color transform settings
  78851. if (this.colorGradingTexture) {
  78852. effect.setTexture("txColorTransform", this.colorGradingTexture);
  78853. var textureSize = this.colorGradingTexture.getSize().height;
  78854. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  78855. 0.5 / textureSize, // textureOffset
  78856. textureSize, // textureSize
  78857. this.colorGradingTexture.level // weight
  78858. );
  78859. }
  78860. };
  78861. /**
  78862. * Clones the current image processing instance.
  78863. * @return The cloned image processing
  78864. */
  78865. ImageProcessingConfiguration.prototype.clone = function () {
  78866. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  78867. };
  78868. /**
  78869. * Serializes the current image processing instance to a json representation.
  78870. * @return a JSON representation
  78871. */
  78872. ImageProcessingConfiguration.prototype.serialize = function () {
  78873. return BABYLON.SerializationHelper.Serialize(this);
  78874. };
  78875. /**
  78876. * Parses the image processing from a json representation.
  78877. * @param source the JSON source to parse
  78878. * @return The parsed image processing
  78879. */
  78880. ImageProcessingConfiguration.Parse = function (source) {
  78881. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  78882. };
  78883. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  78884. /**
  78885. * Used to apply the vignette as a mix with the pixel color.
  78886. */
  78887. get: function () {
  78888. return this._VIGNETTEMODE_MULTIPLY;
  78889. },
  78890. enumerable: true,
  78891. configurable: true
  78892. });
  78893. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  78894. /**
  78895. * Used to apply the vignette as a replacement of the pixel color.
  78896. */
  78897. get: function () {
  78898. return this._VIGNETTEMODE_OPAQUE;
  78899. },
  78900. enumerable: true,
  78901. configurable: true
  78902. });
  78903. // Static constants associated to the image processing.
  78904. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  78905. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  78906. __decorate([
  78907. BABYLON.serializeAsColorCurves()
  78908. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  78909. __decorate([
  78910. BABYLON.serialize()
  78911. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  78912. __decorate([
  78913. BABYLON.serializeAsTexture()
  78914. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  78915. __decorate([
  78916. BABYLON.serialize()
  78917. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  78918. __decorate([
  78919. BABYLON.serialize()
  78920. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  78921. __decorate([
  78922. BABYLON.serialize()
  78923. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  78924. __decorate([
  78925. BABYLON.serialize()
  78926. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  78927. __decorate([
  78928. BABYLON.serialize()
  78929. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  78930. __decorate([
  78931. BABYLON.serialize()
  78932. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  78933. __decorate([
  78934. BABYLON.serialize()
  78935. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  78936. __decorate([
  78937. BABYLON.serialize()
  78938. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  78939. __decorate([
  78940. BABYLON.serialize()
  78941. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  78942. __decorate([
  78943. BABYLON.serialize()
  78944. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  78945. __decorate([
  78946. BABYLON.serializeAsColor4()
  78947. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  78948. __decorate([
  78949. BABYLON.serialize()
  78950. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  78951. __decorate([
  78952. BABYLON.serialize()
  78953. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  78954. __decorate([
  78955. BABYLON.serialize()
  78956. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  78957. __decorate([
  78958. BABYLON.serialize()
  78959. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  78960. __decorate([
  78961. BABYLON.serialize()
  78962. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  78963. return ImageProcessingConfiguration;
  78964. }());
  78965. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  78966. })(BABYLON || (BABYLON = {}));
  78967. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  78968. var BABYLON;
  78969. (function (BABYLON) {
  78970. /**
  78971. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  78972. * It can help converting any input color in a desired output one. This can then be used to create effects
  78973. * from sepia, black and white to sixties or futuristic rendering...
  78974. *
  78975. * The only supported format is currently 3dl.
  78976. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  78977. */
  78978. var ColorGradingTexture = /** @class */ (function (_super) {
  78979. __extends(ColorGradingTexture, _super);
  78980. /**
  78981. * Instantiates a ColorGradingTexture from the following parameters.
  78982. *
  78983. * @param url The location of the color gradind data (currently only supporting 3dl)
  78984. * @param scene The scene the texture will be used in
  78985. */
  78986. function ColorGradingTexture(url, scene) {
  78987. var _this = _super.call(this, scene) || this;
  78988. if (!url) {
  78989. return _this;
  78990. }
  78991. _this._engine = scene.getEngine();
  78992. _this._textureMatrix = BABYLON.Matrix.Identity();
  78993. _this.name = url;
  78994. _this.url = url;
  78995. _this.hasAlpha = false;
  78996. _this.isCube = false;
  78997. _this.is3D = _this._engine.webGLVersion > 1;
  78998. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78999. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79000. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79001. _this.anisotropicFilteringLevel = 1;
  79002. _this._texture = _this._getFromCache(url, true);
  79003. if (!_this._texture) {
  79004. if (!scene.useDelayedTextureLoading) {
  79005. _this.loadTexture();
  79006. }
  79007. else {
  79008. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79009. }
  79010. }
  79011. return _this;
  79012. }
  79013. /**
  79014. * Returns the texture matrix used in most of the material.
  79015. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  79016. */
  79017. ColorGradingTexture.prototype.getTextureMatrix = function () {
  79018. return this._textureMatrix;
  79019. };
  79020. /**
  79021. * Occurs when the file being loaded is a .3dl LUT file.
  79022. */
  79023. ColorGradingTexture.prototype.load3dlTexture = function () {
  79024. var engine = this._engine;
  79025. var texture;
  79026. if (engine.webGLVersion === 1) {
  79027. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79028. }
  79029. else {
  79030. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79031. }
  79032. this._texture = texture;
  79033. var callback = function (text) {
  79034. if (typeof text !== "string") {
  79035. return;
  79036. }
  79037. var data = null;
  79038. var tempData = null;
  79039. var line;
  79040. var lines = text.split('\n');
  79041. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  79042. var maxColor = 0;
  79043. for (var i = 0; i < lines.length; i++) {
  79044. line = lines[i];
  79045. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  79046. continue;
  79047. if (line.indexOf('#') === 0)
  79048. continue;
  79049. var words = line.split(" ");
  79050. if (size === 0) {
  79051. // Number of space + one
  79052. size = words.length;
  79053. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  79054. tempData = new Float32Array(size * size * size * 4);
  79055. continue;
  79056. }
  79057. if (size != 0) {
  79058. var r = Math.max(parseInt(words[0]), 0);
  79059. var g = Math.max(parseInt(words[1]), 0);
  79060. var b = Math.max(parseInt(words[2]), 0);
  79061. maxColor = Math.max(r, maxColor);
  79062. maxColor = Math.max(g, maxColor);
  79063. maxColor = Math.max(b, maxColor);
  79064. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  79065. if (tempData) {
  79066. tempData[pixelStorageIndex + 0] = r;
  79067. tempData[pixelStorageIndex + 1] = g;
  79068. tempData[pixelStorageIndex + 2] = b;
  79069. }
  79070. pixelIndexSlice++;
  79071. if (pixelIndexSlice % size == 0) {
  79072. pixelIndexH++;
  79073. pixelIndexSlice = 0;
  79074. if (pixelIndexH % size == 0) {
  79075. pixelIndexW++;
  79076. pixelIndexH = 0;
  79077. }
  79078. }
  79079. }
  79080. }
  79081. if (tempData && data) {
  79082. for (var i = 0; i < tempData.length; i++) {
  79083. if (i > 0 && (i + 1) % 4 === 0) {
  79084. data[i] = 255;
  79085. }
  79086. else {
  79087. var value = tempData[i];
  79088. data[i] = (value / maxColor * 255);
  79089. }
  79090. }
  79091. }
  79092. if (texture.is3D) {
  79093. texture.updateSize(size, size, size);
  79094. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79095. }
  79096. else {
  79097. texture.updateSize(size * size, size);
  79098. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  79099. }
  79100. };
  79101. var scene = this.getScene();
  79102. if (scene) {
  79103. scene._loadFile(this.url, callback);
  79104. }
  79105. else {
  79106. this._engine._loadFile(this.url, callback);
  79107. }
  79108. return this._texture;
  79109. };
  79110. /**
  79111. * Starts the loading process of the texture.
  79112. */
  79113. ColorGradingTexture.prototype.loadTexture = function () {
  79114. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  79115. this.load3dlTexture();
  79116. }
  79117. };
  79118. /**
  79119. * Clones the color gradind texture.
  79120. */
  79121. ColorGradingTexture.prototype.clone = function () {
  79122. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  79123. // Base texture
  79124. newTexture.level = this.level;
  79125. return newTexture;
  79126. };
  79127. /**
  79128. * Called during delayed load for textures.
  79129. */
  79130. ColorGradingTexture.prototype.delayLoad = function () {
  79131. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79132. return;
  79133. }
  79134. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79135. this._texture = this._getFromCache(this.url, true);
  79136. if (!this._texture) {
  79137. this.loadTexture();
  79138. }
  79139. };
  79140. /**
  79141. * Parses a color grading texture serialized by Babylon.
  79142. * @param parsedTexture The texture information being parsedTexture
  79143. * @param scene The scene to load the texture in
  79144. * @param rootUrl The root url of the data assets to load
  79145. * @return A color gradind texture
  79146. */
  79147. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79148. var texture = null;
  79149. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79150. texture = new ColorGradingTexture(parsedTexture.name, scene);
  79151. texture.name = parsedTexture.name;
  79152. texture.level = parsedTexture.level;
  79153. }
  79154. return texture;
  79155. };
  79156. /**
  79157. * Serializes the LUT texture to json format.
  79158. */
  79159. ColorGradingTexture.prototype.serialize = function () {
  79160. if (!this.name) {
  79161. return null;
  79162. }
  79163. var serializationObject = {};
  79164. serializationObject.name = this.name;
  79165. serializationObject.level = this.level;
  79166. serializationObject.customType = "BABYLON.ColorGradingTexture";
  79167. return serializationObject;
  79168. };
  79169. /**
  79170. * Empty line regex stored for GC.
  79171. */
  79172. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  79173. return ColorGradingTexture;
  79174. }(BABYLON.BaseTexture));
  79175. BABYLON.ColorGradingTexture = ColorGradingTexture;
  79176. })(BABYLON || (BABYLON = {}));
  79177. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  79178. var BABYLON;
  79179. (function (BABYLON) {
  79180. /**
  79181. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79182. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79183. * 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;
  79184. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79185. */
  79186. var ColorCurves = /** @class */ (function () {
  79187. function ColorCurves() {
  79188. this._dirty = true;
  79189. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  79190. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  79191. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79192. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  79193. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  79194. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  79195. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  79196. this._globalHue = 30;
  79197. this._globalDensity = 0;
  79198. this._globalSaturation = 0;
  79199. this._globalExposure = 0;
  79200. this._highlightsHue = 30;
  79201. this._highlightsDensity = 0;
  79202. this._highlightsSaturation = 0;
  79203. this._highlightsExposure = 0;
  79204. this._midtonesHue = 30;
  79205. this._midtonesDensity = 0;
  79206. this._midtonesSaturation = 0;
  79207. this._midtonesExposure = 0;
  79208. this._shadowsHue = 30;
  79209. this._shadowsDensity = 0;
  79210. this._shadowsSaturation = 0;
  79211. this._shadowsExposure = 0;
  79212. }
  79213. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  79214. /**
  79215. * Gets the global Hue value.
  79216. * 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).
  79217. */
  79218. get: function () {
  79219. return this._globalHue;
  79220. },
  79221. /**
  79222. * Sets the global Hue value.
  79223. * 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).
  79224. */
  79225. set: function (value) {
  79226. this._globalHue = value;
  79227. this._dirty = true;
  79228. },
  79229. enumerable: true,
  79230. configurable: true
  79231. });
  79232. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  79233. /**
  79234. * Gets the global Density value.
  79235. * 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.
  79236. * Values less than zero provide a filter of opposite hue.
  79237. */
  79238. get: function () {
  79239. return this._globalDensity;
  79240. },
  79241. /**
  79242. * Sets the global Density value.
  79243. * 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.
  79244. * Values less than zero provide a filter of opposite hue.
  79245. */
  79246. set: function (value) {
  79247. this._globalDensity = value;
  79248. this._dirty = true;
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  79254. /**
  79255. * Gets the global Saturation value.
  79256. * 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.
  79257. */
  79258. get: function () {
  79259. return this._globalSaturation;
  79260. },
  79261. /**
  79262. * Sets the global Saturation value.
  79263. * 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.
  79264. */
  79265. set: function (value) {
  79266. this._globalSaturation = value;
  79267. this._dirty = true;
  79268. },
  79269. enumerable: true,
  79270. configurable: true
  79271. });
  79272. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  79273. /**
  79274. * Gets the global Exposure value.
  79275. * 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.
  79276. */
  79277. get: function () {
  79278. return this._globalExposure;
  79279. },
  79280. /**
  79281. * Sets the global Exposure value.
  79282. * 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.
  79283. */
  79284. set: function (value) {
  79285. this._globalExposure = value;
  79286. this._dirty = true;
  79287. },
  79288. enumerable: true,
  79289. configurable: true
  79290. });
  79291. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  79292. /**
  79293. * Gets the highlights Hue value.
  79294. * 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).
  79295. */
  79296. get: function () {
  79297. return this._highlightsHue;
  79298. },
  79299. /**
  79300. * Sets the highlights Hue value.
  79301. * 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).
  79302. */
  79303. set: function (value) {
  79304. this._highlightsHue = value;
  79305. this._dirty = true;
  79306. },
  79307. enumerable: true,
  79308. configurable: true
  79309. });
  79310. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  79311. /**
  79312. * Gets the highlights Density value.
  79313. * 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.
  79314. * Values less than zero provide a filter of opposite hue.
  79315. */
  79316. get: function () {
  79317. return this._highlightsDensity;
  79318. },
  79319. /**
  79320. * Sets the highlights Density value.
  79321. * 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.
  79322. * Values less than zero provide a filter of opposite hue.
  79323. */
  79324. set: function (value) {
  79325. this._highlightsDensity = value;
  79326. this._dirty = true;
  79327. },
  79328. enumerable: true,
  79329. configurable: true
  79330. });
  79331. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  79332. /**
  79333. * Gets the highlights Saturation value.
  79334. * 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.
  79335. */
  79336. get: function () {
  79337. return this._highlightsSaturation;
  79338. },
  79339. /**
  79340. * Sets the highlights Saturation value.
  79341. * 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.
  79342. */
  79343. set: function (value) {
  79344. this._highlightsSaturation = value;
  79345. this._dirty = true;
  79346. },
  79347. enumerable: true,
  79348. configurable: true
  79349. });
  79350. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  79351. /**
  79352. * Gets the highlights Exposure value.
  79353. * 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.
  79354. */
  79355. get: function () {
  79356. return this._highlightsExposure;
  79357. },
  79358. /**
  79359. * Sets the highlights Exposure value.
  79360. * 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.
  79361. */
  79362. set: function (value) {
  79363. this._highlightsExposure = value;
  79364. this._dirty = true;
  79365. },
  79366. enumerable: true,
  79367. configurable: true
  79368. });
  79369. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  79370. /**
  79371. * Gets the midtones Hue value.
  79372. * 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).
  79373. */
  79374. get: function () {
  79375. return this._midtonesHue;
  79376. },
  79377. /**
  79378. * Sets the midtones Hue value.
  79379. * 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).
  79380. */
  79381. set: function (value) {
  79382. this._midtonesHue = value;
  79383. this._dirty = true;
  79384. },
  79385. enumerable: true,
  79386. configurable: true
  79387. });
  79388. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  79389. /**
  79390. * Gets the midtones Density value.
  79391. * 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.
  79392. * Values less than zero provide a filter of opposite hue.
  79393. */
  79394. get: function () {
  79395. return this._midtonesDensity;
  79396. },
  79397. /**
  79398. * Sets the midtones Density value.
  79399. * 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.
  79400. * Values less than zero provide a filter of opposite hue.
  79401. */
  79402. set: function (value) {
  79403. this._midtonesDensity = value;
  79404. this._dirty = true;
  79405. },
  79406. enumerable: true,
  79407. configurable: true
  79408. });
  79409. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  79410. /**
  79411. * Gets the midtones Saturation value.
  79412. * 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.
  79413. */
  79414. get: function () {
  79415. return this._midtonesSaturation;
  79416. },
  79417. /**
  79418. * Sets the midtones Saturation value.
  79419. * 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.
  79420. */
  79421. set: function (value) {
  79422. this._midtonesSaturation = value;
  79423. this._dirty = true;
  79424. },
  79425. enumerable: true,
  79426. configurable: true
  79427. });
  79428. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  79429. /**
  79430. * Gets the midtones Exposure value.
  79431. * 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.
  79432. */
  79433. get: function () {
  79434. return this._midtonesExposure;
  79435. },
  79436. /**
  79437. * Sets the midtones Exposure value.
  79438. * 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.
  79439. */
  79440. set: function (value) {
  79441. this._midtonesExposure = value;
  79442. this._dirty = true;
  79443. },
  79444. enumerable: true,
  79445. configurable: true
  79446. });
  79447. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  79448. /**
  79449. * Gets the shadows Hue value.
  79450. * 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).
  79451. */
  79452. get: function () {
  79453. return this._shadowsHue;
  79454. },
  79455. /**
  79456. * Sets the shadows Hue value.
  79457. * 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).
  79458. */
  79459. set: function (value) {
  79460. this._shadowsHue = value;
  79461. this._dirty = true;
  79462. },
  79463. enumerable: true,
  79464. configurable: true
  79465. });
  79466. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  79467. /**
  79468. * Gets the shadows Density value.
  79469. * 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.
  79470. * Values less than zero provide a filter of opposite hue.
  79471. */
  79472. get: function () {
  79473. return this._shadowsDensity;
  79474. },
  79475. /**
  79476. * Sets the shadows Density value.
  79477. * 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.
  79478. * Values less than zero provide a filter of opposite hue.
  79479. */
  79480. set: function (value) {
  79481. this._shadowsDensity = value;
  79482. this._dirty = true;
  79483. },
  79484. enumerable: true,
  79485. configurable: true
  79486. });
  79487. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  79488. /**
  79489. * Gets the shadows Saturation value.
  79490. * 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.
  79491. */
  79492. get: function () {
  79493. return this._shadowsSaturation;
  79494. },
  79495. /**
  79496. * Sets the shadows Saturation value.
  79497. * 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.
  79498. */
  79499. set: function (value) {
  79500. this._shadowsSaturation = value;
  79501. this._dirty = true;
  79502. },
  79503. enumerable: true,
  79504. configurable: true
  79505. });
  79506. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  79507. /**
  79508. * Gets the shadows Exposure value.
  79509. * 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.
  79510. */
  79511. get: function () {
  79512. return this._shadowsExposure;
  79513. },
  79514. /**
  79515. * Sets the shadows Exposure value.
  79516. * 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.
  79517. */
  79518. set: function (value) {
  79519. this._shadowsExposure = value;
  79520. this._dirty = true;
  79521. },
  79522. enumerable: true,
  79523. configurable: true
  79524. });
  79525. ColorCurves.prototype.getClassName = function () {
  79526. return "ColorCurves";
  79527. };
  79528. /**
  79529. * Binds the color curves to the shader.
  79530. * @param colorCurves The color curve to bind
  79531. * @param effect The effect to bind to
  79532. */
  79533. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  79534. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  79535. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  79536. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  79537. if (colorCurves._dirty) {
  79538. colorCurves._dirty = false;
  79539. // Fill in global info.
  79540. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  79541. // Compute highlights info.
  79542. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  79543. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  79544. // Compute midtones info.
  79545. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  79546. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  79547. // Compute shadows info.
  79548. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  79549. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  79550. // Compute deltas (neutral is midtones).
  79551. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  79552. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  79553. }
  79554. if (effect) {
  79555. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  79556. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  79557. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  79558. }
  79559. };
  79560. /**
  79561. * Prepare the list of uniforms associated with the ColorCurves effects.
  79562. * @param uniformsList The list of uniforms used in the effect
  79563. */
  79564. ColorCurves.PrepareUniforms = function (uniformsList) {
  79565. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  79566. };
  79567. /**
  79568. * Returns color grading data based on a hue, density, saturation and exposure value.
  79569. * @param filterHue The hue of the color filter.
  79570. * @param filterDensity The density of the color filter.
  79571. * @param saturation The saturation.
  79572. * @param exposure The exposure.
  79573. * @param result The result data container.
  79574. */
  79575. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  79576. if (hue == null) {
  79577. return;
  79578. }
  79579. hue = ColorCurves.clamp(hue, 0, 360);
  79580. density = ColorCurves.clamp(density, -100, 100);
  79581. saturation = ColorCurves.clamp(saturation, -100, 100);
  79582. exposure = ColorCurves.clamp(exposure, -100, 100);
  79583. // Remap the slider/config filter density with non-linear mapping and also scale by half
  79584. // so that the maximum filter density is only 50% control. This provides fine control
  79585. // for small values and reasonable range.
  79586. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  79587. density *= 0.5;
  79588. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  79589. if (density < 0) {
  79590. density *= -1;
  79591. hue = (hue + 180) % 360;
  79592. }
  79593. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  79594. result.scaleToRef(2, result);
  79595. result.a = 1 + 0.01 * saturation;
  79596. };
  79597. /**
  79598. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  79599. * @param value The input slider value in range [-100,100].
  79600. * @returns Adjusted value.
  79601. */
  79602. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  79603. value /= 100;
  79604. var x = Math.abs(value);
  79605. x = Math.pow(x, 2);
  79606. if (value < 0) {
  79607. x *= -1;
  79608. }
  79609. x *= 100;
  79610. return x;
  79611. };
  79612. /**
  79613. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  79614. * @param hue The hue (H) input.
  79615. * @param saturation The saturation (S) input.
  79616. * @param brightness The brightness (B) input.
  79617. * @result An RGBA color represented as Vector4.
  79618. */
  79619. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  79620. var h = ColorCurves.clamp(hue, 0, 360);
  79621. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  79622. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  79623. if (s === 0) {
  79624. result.r = v;
  79625. result.g = v;
  79626. result.b = v;
  79627. }
  79628. else {
  79629. // sector 0 to 5
  79630. h /= 60;
  79631. var i = Math.floor(h);
  79632. // fractional part of h
  79633. var f = h - i;
  79634. var p = v * (1 - s);
  79635. var q = v * (1 - s * f);
  79636. var t = v * (1 - s * (1 - f));
  79637. switch (i) {
  79638. case 0:
  79639. result.r = v;
  79640. result.g = t;
  79641. result.b = p;
  79642. break;
  79643. case 1:
  79644. result.r = q;
  79645. result.g = v;
  79646. result.b = p;
  79647. break;
  79648. case 2:
  79649. result.r = p;
  79650. result.g = v;
  79651. result.b = t;
  79652. break;
  79653. case 3:
  79654. result.r = p;
  79655. result.g = q;
  79656. result.b = v;
  79657. break;
  79658. case 4:
  79659. result.r = t;
  79660. result.g = p;
  79661. result.b = v;
  79662. break;
  79663. default: // case 5:
  79664. result.r = v;
  79665. result.g = p;
  79666. result.b = q;
  79667. break;
  79668. }
  79669. }
  79670. result.a = 1;
  79671. };
  79672. /**
  79673. * Returns a value clamped between min and max
  79674. * @param value The value to clamp
  79675. * @param min The minimum of value
  79676. * @param max The maximum of value
  79677. * @returns The clamped value.
  79678. */
  79679. ColorCurves.clamp = function (value, min, max) {
  79680. return Math.min(Math.max(value, min), max);
  79681. };
  79682. /**
  79683. * Clones the current color curve instance.
  79684. * @return The cloned curves
  79685. */
  79686. ColorCurves.prototype.clone = function () {
  79687. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  79688. };
  79689. /**
  79690. * Serializes the current color curve instance to a json representation.
  79691. * @return a JSON representation
  79692. */
  79693. ColorCurves.prototype.serialize = function () {
  79694. return BABYLON.SerializationHelper.Serialize(this);
  79695. };
  79696. /**
  79697. * Parses the color curve from a json representation.
  79698. * @param source the JSON source to parse
  79699. * @return The parsed curves
  79700. */
  79701. ColorCurves.Parse = function (source) {
  79702. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  79703. };
  79704. __decorate([
  79705. BABYLON.serialize()
  79706. ], ColorCurves.prototype, "_globalHue", void 0);
  79707. __decorate([
  79708. BABYLON.serialize()
  79709. ], ColorCurves.prototype, "_globalDensity", void 0);
  79710. __decorate([
  79711. BABYLON.serialize()
  79712. ], ColorCurves.prototype, "_globalSaturation", void 0);
  79713. __decorate([
  79714. BABYLON.serialize()
  79715. ], ColorCurves.prototype, "_globalExposure", void 0);
  79716. __decorate([
  79717. BABYLON.serialize()
  79718. ], ColorCurves.prototype, "_highlightsHue", void 0);
  79719. __decorate([
  79720. BABYLON.serialize()
  79721. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  79722. __decorate([
  79723. BABYLON.serialize()
  79724. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  79725. __decorate([
  79726. BABYLON.serialize()
  79727. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  79728. __decorate([
  79729. BABYLON.serialize()
  79730. ], ColorCurves.prototype, "_midtonesHue", void 0);
  79731. __decorate([
  79732. BABYLON.serialize()
  79733. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  79734. __decorate([
  79735. BABYLON.serialize()
  79736. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  79737. __decorate([
  79738. BABYLON.serialize()
  79739. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  79740. return ColorCurves;
  79741. }());
  79742. BABYLON.ColorCurves = ColorCurves;
  79743. })(BABYLON || (BABYLON = {}));
  79744. //# sourceMappingURL=babylon.colorCurves.js.map
  79745. var BABYLON;
  79746. (function (BABYLON) {
  79747. var RefractionPostProcess = /** @class */ (function (_super) {
  79748. __extends(RefractionPostProcess, _super);
  79749. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  79750. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  79751. _this.color = color;
  79752. _this.depth = depth;
  79753. _this.colorLevel = colorLevel;
  79754. _this._ownRefractionTexture = true;
  79755. _this.onActivateObservable.add(function (cam) {
  79756. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  79757. });
  79758. _this.onApplyObservable.add(function (effect) {
  79759. effect.setColor3("baseColor", _this.color);
  79760. effect.setFloat("depth", _this.depth);
  79761. effect.setFloat("colorLevel", _this.colorLevel);
  79762. effect.setTexture("refractionSampler", _this._refTexture);
  79763. });
  79764. return _this;
  79765. }
  79766. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  79767. /**
  79768. * Gets or sets the refraction texture
  79769. * Please note that you are responsible for disposing the texture if you set it manually
  79770. */
  79771. get: function () {
  79772. return this._refTexture;
  79773. },
  79774. set: function (value) {
  79775. if (this._refTexture && this._ownRefractionTexture) {
  79776. this._refTexture.dispose();
  79777. }
  79778. this._refTexture = value;
  79779. this._ownRefractionTexture = false;
  79780. },
  79781. enumerable: true,
  79782. configurable: true
  79783. });
  79784. // Methods
  79785. RefractionPostProcess.prototype.dispose = function (camera) {
  79786. if (this._refTexture && this._ownRefractionTexture) {
  79787. this._refTexture.dispose();
  79788. this._refTexture = null;
  79789. }
  79790. _super.prototype.dispose.call(this, camera);
  79791. };
  79792. return RefractionPostProcess;
  79793. }(BABYLON.PostProcess));
  79794. BABYLON.RefractionPostProcess = RefractionPostProcess;
  79795. })(BABYLON || (BABYLON = {}));
  79796. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  79797. var BABYLON;
  79798. (function (BABYLON) {
  79799. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  79800. __extends(BlackAndWhitePostProcess, _super);
  79801. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  79802. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  79803. _this.degree = 1;
  79804. _this.onApplyObservable.add(function (effect) {
  79805. effect.setFloat("degree", _this.degree);
  79806. });
  79807. return _this;
  79808. }
  79809. return BlackAndWhitePostProcess;
  79810. }(BABYLON.PostProcess));
  79811. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  79812. })(BABYLON || (BABYLON = {}));
  79813. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  79814. var BABYLON;
  79815. (function (BABYLON) {
  79816. /**
  79817. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  79818. * input texture to perform effects such as edge detection or sharpening
  79819. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  79820. */
  79821. var ConvolutionPostProcess = /** @class */ (function (_super) {
  79822. __extends(ConvolutionPostProcess, _super);
  79823. /**
  79824. * Creates a new instance ConvolutionPostProcess
  79825. * @param name The name of the effect.
  79826. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  79827. * @param options The required width/height ratio to downsize to before computing the render pass.
  79828. * @param camera The camera to apply the render pass to.
  79829. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  79830. * @param engine The engine which the post process will be applied. (default: current engine)
  79831. * @param reusable If the post process can be reused on the same frame. (default: false)
  79832. * @param textureType Type of textures used when performing the post process. (default: 0)
  79833. */
  79834. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  79835. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79836. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79837. _this.kernel = kernel;
  79838. _this.onApply = function (effect) {
  79839. effect.setFloat2("screenSize", _this.width, _this.height);
  79840. effect.setArray("kernel", _this.kernel);
  79841. };
  79842. return _this;
  79843. }
  79844. // Statics
  79845. /**
  79846. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79847. */
  79848. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  79849. /**
  79850. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79851. */
  79852. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  79853. /**
  79854. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79855. */
  79856. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  79857. /**
  79858. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79859. */
  79860. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  79861. /**
  79862. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79863. */
  79864. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  79865. /**
  79866. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  79867. */
  79868. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  79869. return ConvolutionPostProcess;
  79870. }(BABYLON.PostProcess));
  79871. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  79872. })(BABYLON || (BABYLON = {}));
  79873. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  79874. var BABYLON;
  79875. (function (BABYLON) {
  79876. var FilterPostProcess = /** @class */ (function (_super) {
  79877. __extends(FilterPostProcess, _super);
  79878. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  79879. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  79880. _this.kernelMatrix = kernelMatrix;
  79881. _this.onApply = function (effect) {
  79882. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  79883. };
  79884. return _this;
  79885. }
  79886. return FilterPostProcess;
  79887. }(BABYLON.PostProcess));
  79888. BABYLON.FilterPostProcess = FilterPostProcess;
  79889. })(BABYLON || (BABYLON = {}));
  79890. //# sourceMappingURL=babylon.filterPostProcess.js.map
  79891. var BABYLON;
  79892. (function (BABYLON) {
  79893. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  79894. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  79895. __extends(VolumetricLightScatteringPostProcess, _super);
  79896. /**
  79897. * @constructor
  79898. * @param {string} name - The post-process name
  79899. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  79900. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  79901. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  79902. * @param {number} samples - The post-process quality, default 100
  79903. * @param {number} samplingMode - The post-process filtering mode
  79904. * @param {BABYLON.Engine} engine - The babylon engine
  79905. * @param {boolean} reusable - If the post-process is reusable
  79906. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  79907. */
  79908. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  79909. if (samples === void 0) { samples = 100; }
  79910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79911. 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;
  79912. _this._screenCoordinates = BABYLON.Vector2.Zero();
  79913. /**
  79914. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  79915. */
  79916. _this.customMeshPosition = BABYLON.Vector3.Zero();
  79917. /**
  79918. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  79919. */
  79920. _this.useCustomMeshPosition = false;
  79921. /**
  79922. * If the post-process should inverse the light scattering direction
  79923. */
  79924. _this.invert = true;
  79925. /**
  79926. * Array containing the excluded meshes not rendered in the internal pass
  79927. */
  79928. _this.excludedMeshes = new Array();
  79929. /**
  79930. * Controls the overall intensity of the post-process
  79931. */
  79932. _this.exposure = 0.3;
  79933. /**
  79934. * Dissipates each sample's contribution in range [0, 1]
  79935. */
  79936. _this.decay = 0.96815;
  79937. /**
  79938. * Controls the overall intensity of each sample
  79939. */
  79940. _this.weight = 0.58767;
  79941. /**
  79942. * Controls the density of each sample
  79943. */
  79944. _this.density = 0.926;
  79945. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  79946. engine = scene.getEngine();
  79947. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  79948. // Configure mesh
  79949. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  79950. // Configure
  79951. _this._createPass(scene, ratio.passRatio || ratio);
  79952. _this.onActivate = function (camera) {
  79953. if (!_this.isSupported) {
  79954. _this.dispose(camera);
  79955. }
  79956. _this.onActivate = null;
  79957. };
  79958. _this.onApplyObservable.add(function (effect) {
  79959. _this._updateMeshScreenCoordinates(scene);
  79960. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  79961. effect.setFloat("exposure", _this.exposure);
  79962. effect.setFloat("decay", _this.decay);
  79963. effect.setFloat("weight", _this.weight);
  79964. effect.setFloat("density", _this.density);
  79965. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  79966. });
  79967. return _this;
  79968. }
  79969. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  79970. get: function () {
  79971. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79972. return false;
  79973. },
  79974. set: function (useDiffuseColor) {
  79975. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  79976. },
  79977. enumerable: true,
  79978. configurable: true
  79979. });
  79980. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  79981. return "VolumetricLightScatteringPostProcess";
  79982. };
  79983. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  79984. var mesh = subMesh.getMesh();
  79985. // Render this.mesh as default
  79986. if (mesh === this.mesh && mesh.material) {
  79987. return mesh.material.isReady(mesh);
  79988. }
  79989. var defines = [];
  79990. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79991. var material = subMesh.getMaterial();
  79992. // Alpha test
  79993. if (material) {
  79994. if (material.needAlphaTesting()) {
  79995. defines.push("#define ALPHATEST");
  79996. }
  79997. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79998. attribs.push(BABYLON.VertexBuffer.UVKind);
  79999. defines.push("#define UV1");
  80000. }
  80001. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  80002. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80003. defines.push("#define UV2");
  80004. }
  80005. }
  80006. // Bones
  80007. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  80008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  80009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  80010. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  80011. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  80012. }
  80013. else {
  80014. defines.push("#define NUM_BONE_INFLUENCERS 0");
  80015. }
  80016. // Instances
  80017. if (useInstances) {
  80018. defines.push("#define INSTANCES");
  80019. attribs.push("world0");
  80020. attribs.push("world1");
  80021. attribs.push("world2");
  80022. attribs.push("world3");
  80023. }
  80024. // Get correct effect
  80025. var join = defines.join("\n");
  80026. if (this._cachedDefines !== join) {
  80027. this._cachedDefines = join;
  80028. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  80029. }
  80030. return this._volumetricLightScatteringPass.isReady();
  80031. };
  80032. /**
  80033. * Sets the new light position for light scattering effect
  80034. * @param {BABYLON.Vector3} The new custom light position
  80035. */
  80036. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  80037. this.customMeshPosition = position;
  80038. };
  80039. /**
  80040. * Returns the light position for light scattering effect
  80041. * @return {BABYLON.Vector3} The custom light position
  80042. */
  80043. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  80044. return this.customMeshPosition;
  80045. };
  80046. /**
  80047. * Disposes the internal assets and detaches the post-process from the camera
  80048. */
  80049. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  80050. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  80051. if (rttIndex !== -1) {
  80052. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  80053. }
  80054. this._volumetricLightScatteringRTT.dispose();
  80055. _super.prototype.dispose.call(this, camera);
  80056. };
  80057. /**
  80058. * Returns the render target texture used by the post-process
  80059. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  80060. */
  80061. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  80062. return this._volumetricLightScatteringRTT;
  80063. };
  80064. // Private methods
  80065. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  80066. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  80067. return true;
  80068. }
  80069. return false;
  80070. };
  80071. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  80072. var _this = this;
  80073. var engine = scene.getEngine();
  80074. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80075. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80076. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80077. this._volumetricLightScatteringRTT.renderList = null;
  80078. this._volumetricLightScatteringRTT.renderParticles = false;
  80079. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  80080. var camera = this.getCamera();
  80081. if (camera) {
  80082. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80083. }
  80084. else {
  80085. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  80086. }
  80087. // Custom render function for submeshes
  80088. var renderSubMesh = function (subMesh) {
  80089. var mesh = subMesh.getRenderingMesh();
  80090. if (_this._meshExcluded(mesh)) {
  80091. return;
  80092. }
  80093. var material = subMesh.getMaterial();
  80094. if (!material) {
  80095. return;
  80096. }
  80097. var scene = mesh.getScene();
  80098. var engine = scene.getEngine();
  80099. // Culling
  80100. engine.setState(material.backFaceCulling);
  80101. // Managing instances
  80102. var batch = mesh._getInstancesRenderList(subMesh._id);
  80103. if (batch.mustReturn) {
  80104. return;
  80105. }
  80106. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  80107. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  80108. var effect = _this._volumetricLightScatteringPass;
  80109. if (mesh === _this.mesh) {
  80110. if (subMesh.effect) {
  80111. effect = subMesh.effect;
  80112. }
  80113. else {
  80114. effect = material.getEffect();
  80115. }
  80116. }
  80117. engine.enableEffect(effect);
  80118. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  80119. if (mesh === _this.mesh) {
  80120. material.bind(mesh.getWorldMatrix(), mesh);
  80121. }
  80122. else {
  80123. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  80124. // Alpha test
  80125. if (material && material.needAlphaTesting()) {
  80126. var alphaTexture = material.getAlphaTestTexture();
  80127. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  80128. if (alphaTexture) {
  80129. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  80130. }
  80131. }
  80132. // Bones
  80133. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  80134. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  80135. }
  80136. }
  80137. // Draw
  80138. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  80139. }
  80140. };
  80141. // Render target texture callbacks
  80142. var savedSceneClearColor;
  80143. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  80144. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  80145. savedSceneClearColor = scene.clearColor;
  80146. scene.clearColor = sceneClearColor;
  80147. });
  80148. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  80149. scene.clearColor = savedSceneClearColor;
  80150. });
  80151. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  80152. var engine = scene.getEngine();
  80153. var index;
  80154. if (depthOnlySubMeshes.length) {
  80155. engine.setColorWrite(false);
  80156. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  80157. renderSubMesh(depthOnlySubMeshes.data[index]);
  80158. }
  80159. engine.setColorWrite(true);
  80160. }
  80161. for (index = 0; index < opaqueSubMeshes.length; index++) {
  80162. renderSubMesh(opaqueSubMeshes.data[index]);
  80163. }
  80164. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  80165. renderSubMesh(alphaTestSubMeshes.data[index]);
  80166. }
  80167. if (transparentSubMeshes.length) {
  80168. // Sort sub meshes
  80169. for (index = 0; index < transparentSubMeshes.length; index++) {
  80170. var submesh = transparentSubMeshes.data[index];
  80171. var boundingInfo = submesh.getBoundingInfo();
  80172. if (boundingInfo && scene.activeCamera) {
  80173. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  80174. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  80175. }
  80176. }
  80177. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  80178. sortedArray.sort(function (a, b) {
  80179. // Alpha index first
  80180. if (a._alphaIndex > b._alphaIndex) {
  80181. return 1;
  80182. }
  80183. if (a._alphaIndex < b._alphaIndex) {
  80184. return -1;
  80185. }
  80186. // Then distance to camera
  80187. if (a._distanceToCamera < b._distanceToCamera) {
  80188. return 1;
  80189. }
  80190. if (a._distanceToCamera > b._distanceToCamera) {
  80191. return -1;
  80192. }
  80193. return 0;
  80194. });
  80195. // Render sub meshes
  80196. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  80197. for (index = 0; index < sortedArray.length; index++) {
  80198. renderSubMesh(sortedArray[index]);
  80199. }
  80200. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80201. }
  80202. };
  80203. };
  80204. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  80205. var transform = scene.getTransformMatrix();
  80206. var meshPosition;
  80207. if (this.useCustomMeshPosition) {
  80208. meshPosition = this.customMeshPosition;
  80209. }
  80210. else if (this.attachedNode) {
  80211. meshPosition = this.attachedNode.position;
  80212. }
  80213. else {
  80214. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  80215. }
  80216. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  80217. this._screenCoordinates.x = pos.x / this._viewPort.width;
  80218. this._screenCoordinates.y = pos.y / this._viewPort.height;
  80219. if (this.invert)
  80220. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  80221. };
  80222. // Static methods
  80223. /**
  80224. * Creates a default mesh for the Volumeric Light Scattering post-process
  80225. * @param {string} The mesh name
  80226. * @param {BABYLON.Scene} The scene where to create the mesh
  80227. * @return {BABYLON.Mesh} the default mesh
  80228. */
  80229. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  80230. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  80231. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  80232. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  80233. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  80234. mesh.material = material;
  80235. return mesh;
  80236. };
  80237. __decorate([
  80238. BABYLON.serializeAsVector3()
  80239. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  80240. __decorate([
  80241. BABYLON.serialize()
  80242. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  80243. __decorate([
  80244. BABYLON.serialize()
  80245. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  80246. __decorate([
  80247. BABYLON.serializeAsMeshReference()
  80248. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  80249. __decorate([
  80250. BABYLON.serialize()
  80251. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  80252. __decorate([
  80253. BABYLON.serialize()
  80254. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  80255. __decorate([
  80256. BABYLON.serialize()
  80257. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  80258. __decorate([
  80259. BABYLON.serialize()
  80260. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  80261. __decorate([
  80262. BABYLON.serialize()
  80263. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  80264. return VolumetricLightScatteringPostProcess;
  80265. }(BABYLON.PostProcess));
  80266. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  80267. })(BABYLON || (BABYLON = {}));
  80268. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  80269. //
  80270. // This post-process allows the modification of rendered colors by using
  80271. // a 'look-up table' (LUT). This effect is also called Color Grading.
  80272. //
  80273. // The object needs to be provided an url to a texture containing the color
  80274. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  80275. // Use an image editing software to tweak the LUT to match your needs.
  80276. //
  80277. // For an example of a color LUT, see here:
  80278. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  80279. // For explanations on color grading, see here:
  80280. // http://udn.epicgames.com/Three/ColorGrading.html
  80281. //
  80282. var BABYLON;
  80283. (function (BABYLON) {
  80284. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  80285. __extends(ColorCorrectionPostProcess, _super);
  80286. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  80287. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  80288. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80289. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  80290. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80291. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80292. _this.onApply = function (effect) {
  80293. effect.setTexture("colorTable", _this._colorTableTexture);
  80294. };
  80295. return _this;
  80296. }
  80297. return ColorCorrectionPostProcess;
  80298. }(BABYLON.PostProcess));
  80299. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  80300. })(BABYLON || (BABYLON = {}));
  80301. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  80302. var BABYLON;
  80303. (function (BABYLON) {
  80304. /** Defines operator used for tonemapping */
  80305. var TonemappingOperator;
  80306. (function (TonemappingOperator) {
  80307. /** Hable */
  80308. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  80309. /** Reinhard */
  80310. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  80311. /** HejiDawson */
  80312. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  80313. /** Photographic */
  80314. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  80315. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  80316. ;
  80317. /**
  80318. * Defines a post process to apply tone mapping
  80319. */
  80320. var TonemapPostProcess = /** @class */ (function (_super) {
  80321. __extends(TonemapPostProcess, _super);
  80322. /**
  80323. * Creates a new TonemapPostProcess
  80324. * @param name defines the name of the postprocess
  80325. * @param _operator defines the operator to use
  80326. * @param exposureAdjustment defines the required exposure adjustement
  80327. * @param camera defines the camera to use (can be null)
  80328. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  80329. * @param engine defines the hosting engine (can be ignore if camera is set)
  80330. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  80331. */
  80332. function TonemapPostProcess(name, _operator,
  80333. /** Defines the required exposure adjustement */
  80334. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  80335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  80336. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80337. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  80338. _this._operator = _operator;
  80339. _this.exposureAdjustment = exposureAdjustment;
  80340. var defines = "#define ";
  80341. if (_this._operator === TonemappingOperator.Hable)
  80342. defines += "HABLE_TONEMAPPING";
  80343. else if (_this._operator === TonemappingOperator.Reinhard)
  80344. defines += "REINHARD_TONEMAPPING";
  80345. else if (_this._operator === TonemappingOperator.HejiDawson)
  80346. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  80347. else if (_this._operator === TonemappingOperator.Photographic)
  80348. defines += "PHOTOGRAPHIC_TONEMAPPING";
  80349. //sadly a second call to create the effect.
  80350. _this.updateEffect(defines);
  80351. _this.onApply = function (effect) {
  80352. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  80353. };
  80354. return _this;
  80355. }
  80356. return TonemapPostProcess;
  80357. }(BABYLON.PostProcess));
  80358. BABYLON.TonemapPostProcess = TonemapPostProcess;
  80359. })(BABYLON || (BABYLON = {}));
  80360. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  80361. var BABYLON;
  80362. (function (BABYLON) {
  80363. var DisplayPassPostProcess = /** @class */ (function (_super) {
  80364. __extends(DisplayPassPostProcess, _super);
  80365. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  80366. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  80367. }
  80368. return DisplayPassPostProcess;
  80369. }(BABYLON.PostProcess));
  80370. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  80371. })(BABYLON || (BABYLON = {}));
  80372. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  80373. var BABYLON;
  80374. (function (BABYLON) {
  80375. var HighlightsPostProcess = /** @class */ (function (_super) {
  80376. __extends(HighlightsPostProcess, _super);
  80377. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  80378. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80379. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  80380. }
  80381. return HighlightsPostProcess;
  80382. }(BABYLON.PostProcess));
  80383. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  80384. })(BABYLON || (BABYLON = {}));
  80385. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  80386. var BABYLON;
  80387. (function (BABYLON) {
  80388. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  80389. __extends(ImageProcessingPostProcess, _super);
  80390. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  80391. if (camera === void 0) { camera = null; }
  80392. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  80393. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  80394. _this._fromLinearSpace = true;
  80395. /**
  80396. * Defines cache preventing GC.
  80397. */
  80398. _this._defines = {
  80399. IMAGEPROCESSING: false,
  80400. VIGNETTE: false,
  80401. VIGNETTEBLENDMODEMULTIPLY: false,
  80402. VIGNETTEBLENDMODEOPAQUE: false,
  80403. TONEMAPPING: false,
  80404. CONTRAST: false,
  80405. COLORCURVES: false,
  80406. COLORGRADING: false,
  80407. COLORGRADING3D: false,
  80408. FROMLINEARSPACE: false,
  80409. SAMPLER3DGREENDEPTH: false,
  80410. SAMPLER3DBGRMAP: false,
  80411. IMAGEPROCESSINGPOSTPROCESS: false,
  80412. EXPOSURE: false,
  80413. };
  80414. // Setup the configuration as forced by the constructor. This would then not force the
  80415. // scene materials output in linear space and let untouched the default forward pass.
  80416. if (imageProcessingConfiguration) {
  80417. imageProcessingConfiguration.applyByPostProcess = true;
  80418. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  80419. // This will cause the shader to be compiled
  80420. _this.fromLinearSpace = false;
  80421. }
  80422. // Setup the default processing configuration to the scene.
  80423. else {
  80424. _this._attachImageProcessingConfiguration(null, true);
  80425. _this.imageProcessingConfiguration.applyByPostProcess = true;
  80426. }
  80427. _this.onApply = function (effect) {
  80428. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  80429. };
  80430. return _this;
  80431. }
  80432. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  80433. /**
  80434. * Gets the image processing configuration used either in this material.
  80435. */
  80436. get: function () {
  80437. return this._imageProcessingConfiguration;
  80438. },
  80439. /**
  80440. * Sets the Default image processing configuration used either in the this material.
  80441. *
  80442. * If sets to null, the scene one is in use.
  80443. */
  80444. set: function (value) {
  80445. this._attachImageProcessingConfiguration(value);
  80446. },
  80447. enumerable: true,
  80448. configurable: true
  80449. });
  80450. /**
  80451. * Attaches a new image processing configuration to the PBR Material.
  80452. * @param configuration
  80453. */
  80454. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  80455. var _this = this;
  80456. if (doNotBuild === void 0) { doNotBuild = false; }
  80457. if (configuration === this._imageProcessingConfiguration) {
  80458. return;
  80459. }
  80460. // Detaches observer.
  80461. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80462. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80463. }
  80464. // Pick the scene configuration if needed.
  80465. if (!configuration) {
  80466. var scene = null;
  80467. var engine = this.getEngine();
  80468. var camera = this.getCamera();
  80469. if (camera) {
  80470. scene = camera.getScene();
  80471. }
  80472. else if (engine && engine.scenes) {
  80473. var scenes = engine.scenes;
  80474. scene = scenes[scenes.length - 1];
  80475. }
  80476. else {
  80477. scene = BABYLON.Engine.LastCreatedScene;
  80478. }
  80479. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  80480. }
  80481. else {
  80482. this._imageProcessingConfiguration = configuration;
  80483. }
  80484. // Attaches observer.
  80485. if (this._imageProcessingConfiguration) {
  80486. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80487. _this._updateParameters();
  80488. });
  80489. }
  80490. // Ensure the effect will be rebuilt.
  80491. if (!doNotBuild) {
  80492. this._updateParameters();
  80493. }
  80494. };
  80495. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  80496. /**
  80497. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80498. */
  80499. get: function () {
  80500. return this.imageProcessingConfiguration.colorCurves;
  80501. },
  80502. /**
  80503. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  80504. */
  80505. set: function (value) {
  80506. this.imageProcessingConfiguration.colorCurves = value;
  80507. },
  80508. enumerable: true,
  80509. configurable: true
  80510. });
  80511. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  80512. /**
  80513. * Gets wether the color curves effect is enabled.
  80514. */
  80515. get: function () {
  80516. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80517. },
  80518. /**
  80519. * Sets wether the color curves effect is enabled.
  80520. */
  80521. set: function (value) {
  80522. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80523. },
  80524. enumerable: true,
  80525. configurable: true
  80526. });
  80527. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  80528. /**
  80529. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80530. */
  80531. get: function () {
  80532. return this.imageProcessingConfiguration.colorGradingTexture;
  80533. },
  80534. /**
  80535. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  80536. */
  80537. set: function (value) {
  80538. this.imageProcessingConfiguration.colorGradingTexture = value;
  80539. },
  80540. enumerable: true,
  80541. configurable: true
  80542. });
  80543. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  80544. /**
  80545. * Gets wether the color grading effect is enabled.
  80546. */
  80547. get: function () {
  80548. return this.imageProcessingConfiguration.colorGradingEnabled;
  80549. },
  80550. /**
  80551. * Gets wether the color grading effect is enabled.
  80552. */
  80553. set: function (value) {
  80554. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80555. },
  80556. enumerable: true,
  80557. configurable: true
  80558. });
  80559. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  80560. /**
  80561. * Gets exposure used in the effect.
  80562. */
  80563. get: function () {
  80564. return this.imageProcessingConfiguration.exposure;
  80565. },
  80566. /**
  80567. * Sets exposure used in the effect.
  80568. */
  80569. set: function (value) {
  80570. this.imageProcessingConfiguration.exposure = value;
  80571. },
  80572. enumerable: true,
  80573. configurable: true
  80574. });
  80575. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  80576. /**
  80577. * Gets wether tonemapping is enabled or not.
  80578. */
  80579. get: function () {
  80580. return this._imageProcessingConfiguration.toneMappingEnabled;
  80581. },
  80582. /**
  80583. * Sets wether tonemapping is enabled or not
  80584. */
  80585. set: function (value) {
  80586. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80587. },
  80588. enumerable: true,
  80589. configurable: true
  80590. });
  80591. ;
  80592. ;
  80593. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  80594. /**
  80595. * Gets contrast used in the effect.
  80596. */
  80597. get: function () {
  80598. return this.imageProcessingConfiguration.contrast;
  80599. },
  80600. /**
  80601. * Sets contrast used in the effect.
  80602. */
  80603. set: function (value) {
  80604. this.imageProcessingConfiguration.contrast = value;
  80605. },
  80606. enumerable: true,
  80607. configurable: true
  80608. });
  80609. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  80610. /**
  80611. * Gets Vignette stretch size.
  80612. */
  80613. get: function () {
  80614. return this.imageProcessingConfiguration.vignetteStretch;
  80615. },
  80616. /**
  80617. * Sets Vignette stretch size.
  80618. */
  80619. set: function (value) {
  80620. this.imageProcessingConfiguration.vignetteStretch = value;
  80621. },
  80622. enumerable: true,
  80623. configurable: true
  80624. });
  80625. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  80626. /**
  80627. * Gets Vignette centre X Offset.
  80628. */
  80629. get: function () {
  80630. return this.imageProcessingConfiguration.vignetteCentreX;
  80631. },
  80632. /**
  80633. * Sets Vignette centre X Offset.
  80634. */
  80635. set: function (value) {
  80636. this.imageProcessingConfiguration.vignetteCentreX = value;
  80637. },
  80638. enumerable: true,
  80639. configurable: true
  80640. });
  80641. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  80642. /**
  80643. * Gets Vignette centre Y Offset.
  80644. */
  80645. get: function () {
  80646. return this.imageProcessingConfiguration.vignetteCentreY;
  80647. },
  80648. /**
  80649. * Sets Vignette centre Y Offset.
  80650. */
  80651. set: function (value) {
  80652. this.imageProcessingConfiguration.vignetteCentreY = value;
  80653. },
  80654. enumerable: true,
  80655. configurable: true
  80656. });
  80657. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  80658. /**
  80659. * Gets Vignette weight or intensity of the vignette effect.
  80660. */
  80661. get: function () {
  80662. return this.imageProcessingConfiguration.vignetteWeight;
  80663. },
  80664. /**
  80665. * Sets Vignette weight or intensity of the vignette effect.
  80666. */
  80667. set: function (value) {
  80668. this.imageProcessingConfiguration.vignetteWeight = value;
  80669. },
  80670. enumerable: true,
  80671. configurable: true
  80672. });
  80673. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  80674. /**
  80675. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80676. * if vignetteEnabled is set to true.
  80677. */
  80678. get: function () {
  80679. return this.imageProcessingConfiguration.vignetteColor;
  80680. },
  80681. /**
  80682. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  80683. * if vignetteEnabled is set to true.
  80684. */
  80685. set: function (value) {
  80686. this.imageProcessingConfiguration.vignetteColor = value;
  80687. },
  80688. enumerable: true,
  80689. configurable: true
  80690. });
  80691. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  80692. /**
  80693. * Gets Camera field of view used by the Vignette effect.
  80694. */
  80695. get: function () {
  80696. return this.imageProcessingConfiguration.vignetteCameraFov;
  80697. },
  80698. /**
  80699. * Sets Camera field of view used by the Vignette effect.
  80700. */
  80701. set: function (value) {
  80702. this.imageProcessingConfiguration.vignetteCameraFov = value;
  80703. },
  80704. enumerable: true,
  80705. configurable: true
  80706. });
  80707. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  80708. /**
  80709. * Gets the vignette blend mode allowing different kind of effect.
  80710. */
  80711. get: function () {
  80712. return this.imageProcessingConfiguration.vignetteBlendMode;
  80713. },
  80714. /**
  80715. * Sets the vignette blend mode allowing different kind of effect.
  80716. */
  80717. set: function (value) {
  80718. this.imageProcessingConfiguration.vignetteBlendMode = value;
  80719. },
  80720. enumerable: true,
  80721. configurable: true
  80722. });
  80723. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  80724. /**
  80725. * Gets wether the vignette effect is enabled.
  80726. */
  80727. get: function () {
  80728. return this.imageProcessingConfiguration.vignetteEnabled;
  80729. },
  80730. /**
  80731. * Sets wether the vignette effect is enabled.
  80732. */
  80733. set: function (value) {
  80734. this.imageProcessingConfiguration.vignetteEnabled = value;
  80735. },
  80736. enumerable: true,
  80737. configurable: true
  80738. });
  80739. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  80740. /**
  80741. * Gets wether the input of the processing is in Gamma or Linear Space.
  80742. */
  80743. get: function () {
  80744. return this._fromLinearSpace;
  80745. },
  80746. /**
  80747. * Sets wether the input of the processing is in Gamma or Linear Space.
  80748. */
  80749. set: function (value) {
  80750. if (this._fromLinearSpace === value) {
  80751. return;
  80752. }
  80753. this._fromLinearSpace = value;
  80754. this._updateParameters();
  80755. },
  80756. enumerable: true,
  80757. configurable: true
  80758. });
  80759. ImageProcessingPostProcess.prototype.getClassName = function () {
  80760. return "ImageProcessingPostProcess";
  80761. };
  80762. ImageProcessingPostProcess.prototype._updateParameters = function () {
  80763. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  80764. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  80765. var defines = "";
  80766. for (var define in this._defines) {
  80767. if (this._defines[define]) {
  80768. defines += "#define " + define + ";\r\n";
  80769. }
  80770. }
  80771. var samplers = ["textureSampler"];
  80772. var uniforms = ["scale"];
  80773. if (BABYLON.ImageProcessingConfiguration) {
  80774. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  80775. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  80776. }
  80777. this.updateEffect(defines, uniforms, samplers);
  80778. };
  80779. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  80780. _super.prototype.dispose.call(this, camera);
  80781. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80782. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80783. }
  80784. if (this._imageProcessingConfiguration) {
  80785. this.imageProcessingConfiguration.applyByPostProcess = false;
  80786. }
  80787. };
  80788. __decorate([
  80789. BABYLON.serialize()
  80790. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  80791. return ImageProcessingPostProcess;
  80792. }(BABYLON.PostProcess));
  80793. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  80794. })(BABYLON || (BABYLON = {}));
  80795. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  80796. var BABYLON;
  80797. (function (BABYLON) {
  80798. /**
  80799. * Class used to store bone information
  80800. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80801. */
  80802. var Bone = /** @class */ (function (_super) {
  80803. __extends(Bone, _super);
  80804. /**
  80805. * Create a new bone
  80806. * @param name defines the bone name
  80807. * @param skeleton defines the parent skeleton
  80808. * @param parentBone defines the parent (can be null if the bone is the root)
  80809. * @param localMatrix defines the local matrix
  80810. * @param restPose defines the rest pose matrix
  80811. * @param baseMatrix defines the base matrix
  80812. * @param index defines index of the bone in the hiearchy
  80813. */
  80814. function Bone(
  80815. /**
  80816. * defines the bone name
  80817. */
  80818. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  80819. if (parentBone === void 0) { parentBone = null; }
  80820. if (localMatrix === void 0) { localMatrix = null; }
  80821. if (restPose === void 0) { restPose = null; }
  80822. if (baseMatrix === void 0) { baseMatrix = null; }
  80823. if (index === void 0) { index = null; }
  80824. var _this = _super.call(this, name, skeleton.getScene()) || this;
  80825. _this.name = name;
  80826. /**
  80827. * Gets the list of child bones
  80828. */
  80829. _this.children = new Array();
  80830. /** Gets the animations associated with this bone */
  80831. _this.animations = new Array();
  80832. /**
  80833. * @hidden Internal only
  80834. * Set this value to map this bone to a different index in the transform matrices
  80835. * Set this value to -1 to exclude the bone from the transform matrices
  80836. */
  80837. _this._index = null;
  80838. _this._absoluteTransform = new BABYLON.Matrix();
  80839. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  80840. _this._scalingDeterminant = 1;
  80841. _this._worldTransform = new BABYLON.Matrix();
  80842. _this._needToDecompose = true;
  80843. _this._needToCompose = false;
  80844. _this._skeleton = skeleton;
  80845. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  80846. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  80847. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  80848. _this._index = index;
  80849. skeleton.bones.push(_this);
  80850. _this.setParent(parentBone, false);
  80851. if (baseMatrix || localMatrix) {
  80852. _this._updateDifferenceMatrix();
  80853. }
  80854. return _this;
  80855. }
  80856. Object.defineProperty(Bone.prototype, "_matrix", {
  80857. /** @hidden */
  80858. get: function () {
  80859. this._compose();
  80860. return this._localMatrix;
  80861. },
  80862. /** @hidden */
  80863. set: function (value) {
  80864. this._localMatrix.copyFrom(value);
  80865. this._needToDecompose = true;
  80866. },
  80867. enumerable: true,
  80868. configurable: true
  80869. });
  80870. // Members
  80871. /**
  80872. * Gets the parent skeleton
  80873. * @returns a skeleton
  80874. */
  80875. Bone.prototype.getSkeleton = function () {
  80876. return this._skeleton;
  80877. };
  80878. /**
  80879. * Gets parent bone
  80880. * @returns a bone or null if the bone is the root of the bone hierarchy
  80881. */
  80882. Bone.prototype.getParent = function () {
  80883. return this._parent;
  80884. };
  80885. /**
  80886. * Sets the parent bone
  80887. * @param parent defines the parent (can be null if the bone is the root)
  80888. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  80889. */
  80890. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  80891. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  80892. if (this._parent === parent) {
  80893. return;
  80894. }
  80895. if (this._parent) {
  80896. var index = this._parent.children.indexOf(this);
  80897. if (index !== -1) {
  80898. this._parent.children.splice(index, 1);
  80899. }
  80900. }
  80901. this._parent = parent;
  80902. if (this._parent) {
  80903. this._parent.children.push(this);
  80904. }
  80905. if (updateDifferenceMatrix) {
  80906. this._updateDifferenceMatrix();
  80907. }
  80908. this.markAsDirty();
  80909. };
  80910. /**
  80911. * Gets the local matrix
  80912. * @returns a matrix
  80913. */
  80914. Bone.prototype.getLocalMatrix = function () {
  80915. this._compose();
  80916. return this._localMatrix;
  80917. };
  80918. /**
  80919. * Gets the base matrix (initial matrix which remains unchanged)
  80920. * @returns a matrix
  80921. */
  80922. Bone.prototype.getBaseMatrix = function () {
  80923. return this._baseMatrix;
  80924. };
  80925. /**
  80926. * Gets the rest pose matrix
  80927. * @returns a matrix
  80928. */
  80929. Bone.prototype.getRestPose = function () {
  80930. return this._restPose;
  80931. };
  80932. /**
  80933. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  80934. */
  80935. Bone.prototype.getWorldMatrix = function () {
  80936. return this._worldTransform;
  80937. };
  80938. /**
  80939. * Sets the local matrix to rest pose matrix
  80940. */
  80941. Bone.prototype.returnToRest = function () {
  80942. this.updateMatrix(this._restPose.clone());
  80943. };
  80944. /**
  80945. * Gets the inverse of the absolute transform matrix.
  80946. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  80947. * @returns a matrix
  80948. */
  80949. Bone.prototype.getInvertedAbsoluteTransform = function () {
  80950. return this._invertedAbsoluteTransform;
  80951. };
  80952. /**
  80953. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  80954. * @returns a matrix
  80955. */
  80956. Bone.prototype.getAbsoluteTransform = function () {
  80957. return this._absoluteTransform;
  80958. };
  80959. Object.defineProperty(Bone.prototype, "position", {
  80960. // Properties (matches AbstractMesh properties)
  80961. /** Gets or sets current position (in local space) */
  80962. get: function () {
  80963. this._decompose();
  80964. return this._localPosition;
  80965. },
  80966. set: function (newPosition) {
  80967. this._decompose();
  80968. this._localPosition.copyFrom(newPosition);
  80969. this._markAsDirtyAndCompose();
  80970. },
  80971. enumerable: true,
  80972. configurable: true
  80973. });
  80974. Object.defineProperty(Bone.prototype, "rotation", {
  80975. /** Gets or sets current rotation (in local space) */
  80976. get: function () {
  80977. return this.getRotation();
  80978. },
  80979. set: function (newRotation) {
  80980. this.setRotation(newRotation);
  80981. },
  80982. enumerable: true,
  80983. configurable: true
  80984. });
  80985. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  80986. /** Gets or sets current rotation quaternion (in local space) */
  80987. get: function () {
  80988. this._decompose();
  80989. return this._localRotation;
  80990. },
  80991. set: function (newRotation) {
  80992. this.setRotationQuaternion(newRotation);
  80993. },
  80994. enumerable: true,
  80995. configurable: true
  80996. });
  80997. Object.defineProperty(Bone.prototype, "scaling", {
  80998. /** Gets or sets current scaling (in local space) */
  80999. get: function () {
  81000. return this.getScale();
  81001. },
  81002. set: function (newScaling) {
  81003. this.setScale(newScaling);
  81004. },
  81005. enumerable: true,
  81006. configurable: true
  81007. });
  81008. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  81009. /**
  81010. * Gets the animation properties override
  81011. */
  81012. get: function () {
  81013. return this._skeleton.animationPropertiesOverride;
  81014. },
  81015. enumerable: true,
  81016. configurable: true
  81017. });
  81018. // Methods
  81019. Bone.prototype._decompose = function () {
  81020. if (!this._needToDecompose) {
  81021. return;
  81022. }
  81023. this._needToDecompose = false;
  81024. if (!this._localScaling) {
  81025. this._localScaling = BABYLON.Vector3.Zero();
  81026. this._localRotation = BABYLON.Quaternion.Zero();
  81027. this._localPosition = BABYLON.Vector3.Zero();
  81028. }
  81029. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  81030. };
  81031. Bone.prototype._compose = function () {
  81032. if (!this._needToCompose) {
  81033. return;
  81034. }
  81035. this._needToCompose = false;
  81036. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  81037. };
  81038. /**
  81039. * Update the base and local matrices
  81040. * @param matrix defines the new base or local matrix
  81041. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  81042. * @param updateLocalMatrix defines if the local matrix should be updated
  81043. */
  81044. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  81045. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  81046. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  81047. this._baseMatrix.copyFrom(matrix);
  81048. if (updateDifferenceMatrix) {
  81049. this._updateDifferenceMatrix();
  81050. }
  81051. if (updateLocalMatrix) {
  81052. this._localMatrix.copyFrom(matrix);
  81053. this._markAsDirtyAndDecompose();
  81054. }
  81055. else {
  81056. this.markAsDirty();
  81057. }
  81058. };
  81059. /** @hidden */
  81060. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  81061. if (updateChildren === void 0) { updateChildren = true; }
  81062. if (!rootMatrix) {
  81063. rootMatrix = this._baseMatrix;
  81064. }
  81065. if (this._parent) {
  81066. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81067. }
  81068. else {
  81069. this._absoluteTransform.copyFrom(rootMatrix);
  81070. }
  81071. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  81072. if (updateChildren) {
  81073. for (var index = 0; index < this.children.length; index++) {
  81074. this.children[index]._updateDifferenceMatrix();
  81075. }
  81076. }
  81077. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  81078. };
  81079. /**
  81080. * Flag the bone as dirty (Forcing it to update everything)
  81081. */
  81082. Bone.prototype.markAsDirty = function () {
  81083. this._currentRenderId++;
  81084. this._childRenderId++;
  81085. this._skeleton._markAsDirty();
  81086. };
  81087. Bone.prototype._markAsDirtyAndCompose = function () {
  81088. this.markAsDirty();
  81089. this._needToCompose = true;
  81090. };
  81091. Bone.prototype._markAsDirtyAndDecompose = function () {
  81092. this.markAsDirty();
  81093. this._needToDecompose = true;
  81094. };
  81095. /**
  81096. * Copy an animation range from another bone
  81097. * @param source defines the source bone
  81098. * @param rangeName defines the range name to copy
  81099. * @param frameOffset defines the frame offset
  81100. * @param rescaleAsRequired defines if rescaling must be applied if required
  81101. * @param skelDimensionsRatio defines the scaling ratio
  81102. * @returns true if operation was successful
  81103. */
  81104. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  81105. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81106. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  81107. // all animation may be coming from a library skeleton, so may need to create animation
  81108. if (this.animations.length === 0) {
  81109. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  81110. this.animations[0].setKeys([]);
  81111. }
  81112. // get animation info / verify there is such a range from the source bone
  81113. var sourceRange = source.animations[0].getRange(rangeName);
  81114. if (!sourceRange) {
  81115. return false;
  81116. }
  81117. var from = sourceRange.from;
  81118. var to = sourceRange.to;
  81119. var sourceKeys = source.animations[0].getKeys();
  81120. // rescaling prep
  81121. var sourceBoneLength = source.length;
  81122. var sourceParent = source.getParent();
  81123. var parent = this.getParent();
  81124. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  81125. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  81126. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  81127. var destKeys = this.animations[0].getKeys();
  81128. // loop vars declaration
  81129. var orig;
  81130. var origTranslation;
  81131. var mat;
  81132. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  81133. orig = sourceKeys[key];
  81134. if (orig.frame >= from && orig.frame <= to) {
  81135. if (rescaleAsRequired) {
  81136. mat = orig.value.clone();
  81137. // scale based on parent ratio, when bone has parent
  81138. if (parentScalingReqd) {
  81139. origTranslation = mat.getTranslation();
  81140. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  81141. // scale based on skeleton dimension ratio when root bone, and value is passed
  81142. }
  81143. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  81144. origTranslation = mat.getTranslation();
  81145. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  81146. // use original when root bone, and no data for skelDimensionsRatio
  81147. }
  81148. else {
  81149. mat = orig.value;
  81150. }
  81151. }
  81152. else {
  81153. mat = orig.value;
  81154. }
  81155. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  81156. }
  81157. }
  81158. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  81159. return true;
  81160. };
  81161. /**
  81162. * Translate the bone in local or world space
  81163. * @param vec The amount to translate the bone
  81164. * @param space The space that the translation is in
  81165. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81166. */
  81167. Bone.prototype.translate = function (vec, space, mesh) {
  81168. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81169. var lm = this.getLocalMatrix();
  81170. if (space == BABYLON.Space.LOCAL) {
  81171. lm.m[12] += vec.x;
  81172. lm.m[13] += vec.y;
  81173. lm.m[14] += vec.z;
  81174. }
  81175. else {
  81176. var wm = null;
  81177. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81178. if (mesh) {
  81179. wm = mesh.getWorldMatrix();
  81180. }
  81181. this._skeleton.computeAbsoluteTransforms();
  81182. var tmat = Bone._tmpMats[0];
  81183. var tvec = Bone._tmpVecs[0];
  81184. if (this._parent) {
  81185. if (mesh && wm) {
  81186. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81187. tmat.multiplyToRef(wm, tmat);
  81188. }
  81189. else {
  81190. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81191. }
  81192. }
  81193. tmat.m[12] = 0;
  81194. tmat.m[13] = 0;
  81195. tmat.m[14] = 0;
  81196. tmat.invert();
  81197. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  81198. lm.m[12] += tvec.x;
  81199. lm.m[13] += tvec.y;
  81200. lm.m[14] += tvec.z;
  81201. }
  81202. this._markAsDirtyAndDecompose();
  81203. };
  81204. /**
  81205. * Set the postion of the bone in local or world space
  81206. * @param position The position to set the bone
  81207. * @param space The space that the position is in
  81208. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81209. */
  81210. Bone.prototype.setPosition = function (position, space, mesh) {
  81211. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81212. var lm = this.getLocalMatrix();
  81213. if (space == BABYLON.Space.LOCAL) {
  81214. lm.m[12] = position.x;
  81215. lm.m[13] = position.y;
  81216. lm.m[14] = position.z;
  81217. }
  81218. else {
  81219. var wm = null;
  81220. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81221. if (mesh) {
  81222. wm = mesh.getWorldMatrix();
  81223. }
  81224. this._skeleton.computeAbsoluteTransforms();
  81225. var tmat = Bone._tmpMats[0];
  81226. var vec = Bone._tmpVecs[0];
  81227. if (this._parent) {
  81228. if (mesh && wm) {
  81229. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81230. tmat.multiplyToRef(wm, tmat);
  81231. }
  81232. else {
  81233. tmat.copyFrom(this._parent.getAbsoluteTransform());
  81234. }
  81235. }
  81236. tmat.invert();
  81237. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  81238. lm.m[12] = vec.x;
  81239. lm.m[13] = vec.y;
  81240. lm.m[14] = vec.z;
  81241. }
  81242. this._markAsDirtyAndDecompose();
  81243. };
  81244. /**
  81245. * Set the absolute position of the bone (world space)
  81246. * @param position The position to set the bone
  81247. * @param mesh The mesh that this bone is attached to
  81248. */
  81249. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  81250. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  81251. };
  81252. /**
  81253. * Scale the bone on the x, y and z axes (in local space)
  81254. * @param x The amount to scale the bone on the x axis
  81255. * @param y The amount to scale the bone on the y axis
  81256. * @param z The amount to scale the bone on the z axis
  81257. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  81258. */
  81259. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  81260. if (scaleChildren === void 0) { scaleChildren = false; }
  81261. var locMat = this.getLocalMatrix();
  81262. // Apply new scaling on top of current local matrix
  81263. var scaleMat = Bone._tmpMats[0];
  81264. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  81265. scaleMat.multiplyToRef(locMat, locMat);
  81266. // Invert scaling matrix and apply the inverse to all children
  81267. scaleMat.invert();
  81268. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  81269. var child = _a[_i];
  81270. var cm = child.getLocalMatrix();
  81271. cm.multiplyToRef(scaleMat, cm);
  81272. cm.m[12] *= x;
  81273. cm.m[13] *= y;
  81274. cm.m[14] *= z;
  81275. child._markAsDirtyAndDecompose();
  81276. }
  81277. this._markAsDirtyAndDecompose();
  81278. if (scaleChildren) {
  81279. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  81280. var child = _c[_b];
  81281. child.scale(x, y, z, scaleChildren);
  81282. }
  81283. }
  81284. };
  81285. /**
  81286. * Set the bone scaling in local space
  81287. * @param scale defines the scaling vector
  81288. */
  81289. Bone.prototype.setScale = function (scale) {
  81290. this._decompose();
  81291. this._localScaling.copyFrom(scale);
  81292. this._markAsDirtyAndCompose();
  81293. };
  81294. /**
  81295. * Gets the current scaling in local space
  81296. * @returns the current scaling vector
  81297. */
  81298. Bone.prototype.getScale = function () {
  81299. this._decompose();
  81300. return this._localScaling;
  81301. };
  81302. /**
  81303. * Gets the current scaling in local space and stores it in a target vector
  81304. * @param result defines the target vector
  81305. */
  81306. Bone.prototype.getScaleToRef = function (result) {
  81307. this._decompose();
  81308. result.copyFrom(this._localScaling);
  81309. };
  81310. /**
  81311. * Set the yaw, pitch, and roll of the bone in local or world space
  81312. * @param yaw The rotation of the bone on the y axis
  81313. * @param pitch The rotation of the bone on the x axis
  81314. * @param roll The rotation of the bone on the z axis
  81315. * @param space The space that the axes of rotation are in
  81316. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81317. */
  81318. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  81319. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81320. if (space === BABYLON.Space.LOCAL) {
  81321. var quat = Bone._tmpQuat;
  81322. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  81323. this.setRotationQuaternion(quat, space, mesh);
  81324. return;
  81325. }
  81326. var rotMatInv = Bone._tmpMats[0];
  81327. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81328. return;
  81329. }
  81330. var rotMat = Bone._tmpMats[1];
  81331. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  81332. rotMatInv.multiplyToRef(rotMat, rotMat);
  81333. this._rotateWithMatrix(rotMat, space, mesh);
  81334. };
  81335. /**
  81336. * Add a rotation to the bone on an axis in local or world space
  81337. * @param axis The axis to rotate the bone on
  81338. * @param amount The amount to rotate the bone
  81339. * @param space The space that the axis is in
  81340. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81341. */
  81342. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  81343. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81344. var rmat = Bone._tmpMats[0];
  81345. rmat.m[12] = 0;
  81346. rmat.m[13] = 0;
  81347. rmat.m[14] = 0;
  81348. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  81349. this._rotateWithMatrix(rmat, space, mesh);
  81350. };
  81351. /**
  81352. * Set the rotation of the bone to a particular axis angle in local or world space
  81353. * @param axis The axis to rotate the bone on
  81354. * @param angle The angle that the bone should be rotated to
  81355. * @param space The space that the axis is in
  81356. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81357. */
  81358. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  81359. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81360. if (space === BABYLON.Space.LOCAL) {
  81361. var quat = Bone._tmpQuat;
  81362. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  81363. this.setRotationQuaternion(quat, space, mesh);
  81364. return;
  81365. }
  81366. var rotMatInv = Bone._tmpMats[0];
  81367. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81368. return;
  81369. }
  81370. var rotMat = Bone._tmpMats[1];
  81371. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  81372. rotMatInv.multiplyToRef(rotMat, rotMat);
  81373. this._rotateWithMatrix(rotMat, space, mesh);
  81374. };
  81375. /**
  81376. * Set the euler rotation of the bone in local of world space
  81377. * @param rotation The euler rotation that the bone should be set to
  81378. * @param space The space that the rotation is in
  81379. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81380. */
  81381. Bone.prototype.setRotation = function (rotation, space, mesh) {
  81382. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81383. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  81384. };
  81385. /**
  81386. * Set the quaternion rotation of the bone in local of world space
  81387. * @param quat The quaternion rotation that the bone should be set to
  81388. * @param space The space that the rotation is in
  81389. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81390. */
  81391. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  81392. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81393. if (space === BABYLON.Space.LOCAL) {
  81394. this._decompose();
  81395. this._localRotation.copyFrom(quat);
  81396. this._markAsDirtyAndCompose();
  81397. return;
  81398. }
  81399. var rotMatInv = Bone._tmpMats[0];
  81400. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81401. return;
  81402. }
  81403. var rotMat = Bone._tmpMats[1];
  81404. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  81405. rotMatInv.multiplyToRef(rotMat, rotMat);
  81406. this._rotateWithMatrix(rotMat, space, mesh);
  81407. };
  81408. /**
  81409. * Set the rotation matrix of the bone in local of world space
  81410. * @param rotMat The rotation matrix that the bone should be set to
  81411. * @param space The space that the rotation is in
  81412. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81413. */
  81414. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  81415. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81416. if (space === BABYLON.Space.LOCAL) {
  81417. var quat = Bone._tmpQuat;
  81418. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  81419. this.setRotationQuaternion(quat, space, mesh);
  81420. return;
  81421. }
  81422. var rotMatInv = Bone._tmpMats[0];
  81423. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  81424. return;
  81425. }
  81426. var rotMat2 = Bone._tmpMats[1];
  81427. rotMat2.copyFrom(rotMat);
  81428. rotMatInv.multiplyToRef(rotMat, rotMat2);
  81429. this._rotateWithMatrix(rotMat2, space, mesh);
  81430. };
  81431. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  81432. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81433. var lmat = this.getLocalMatrix();
  81434. var lx = lmat.m[12];
  81435. var ly = lmat.m[13];
  81436. var lz = lmat.m[14];
  81437. var parent = this.getParent();
  81438. var parentScale = Bone._tmpMats[3];
  81439. var parentScaleInv = Bone._tmpMats[4];
  81440. if (parent && space == BABYLON.Space.WORLD) {
  81441. if (mesh) {
  81442. parentScale.copyFrom(mesh.getWorldMatrix());
  81443. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  81444. }
  81445. else {
  81446. parentScale.copyFrom(parent.getAbsoluteTransform());
  81447. }
  81448. parentScaleInv.copyFrom(parentScale);
  81449. parentScaleInv.invert();
  81450. lmat.multiplyToRef(parentScale, lmat);
  81451. lmat.multiplyToRef(rmat, lmat);
  81452. lmat.multiplyToRef(parentScaleInv, lmat);
  81453. }
  81454. else {
  81455. if (space == BABYLON.Space.WORLD && mesh) {
  81456. parentScale.copyFrom(mesh.getWorldMatrix());
  81457. parentScaleInv.copyFrom(parentScale);
  81458. parentScaleInv.invert();
  81459. lmat.multiplyToRef(parentScale, lmat);
  81460. lmat.multiplyToRef(rmat, lmat);
  81461. lmat.multiplyToRef(parentScaleInv, lmat);
  81462. }
  81463. else {
  81464. lmat.multiplyToRef(rmat, lmat);
  81465. }
  81466. }
  81467. lmat.m[12] = lx;
  81468. lmat.m[13] = ly;
  81469. lmat.m[14] = lz;
  81470. this.computeAbsoluteTransforms();
  81471. this._markAsDirtyAndDecompose();
  81472. };
  81473. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  81474. var scaleMatrix = Bone._tmpMats[2];
  81475. rotMatInv.copyFrom(this.getAbsoluteTransform());
  81476. if (mesh) {
  81477. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  81478. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  81479. }
  81480. rotMatInv.invert();
  81481. if (isNaN(rotMatInv.m[0])) {
  81482. // Matrix failed to invert.
  81483. // This can happen if scale is zero for example.
  81484. return false;
  81485. }
  81486. scaleMatrix.m[0] *= this._scalingDeterminant;
  81487. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  81488. return true;
  81489. };
  81490. /**
  81491. * Get the position of the bone in local or world space
  81492. * @param space The space that the returned position is in
  81493. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81494. * @returns The position of the bone
  81495. */
  81496. Bone.prototype.getPosition = function (space, mesh) {
  81497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81498. if (mesh === void 0) { mesh = null; }
  81499. var pos = BABYLON.Vector3.Zero();
  81500. this.getPositionToRef(space, mesh, pos);
  81501. return pos;
  81502. };
  81503. /**
  81504. * Copy the position of the bone to a vector3 in local or world space
  81505. * @param space The space that the returned position is in
  81506. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81507. * @param result The vector3 to copy the position to
  81508. */
  81509. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  81510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81511. if (space == BABYLON.Space.LOCAL) {
  81512. var lm = this.getLocalMatrix();
  81513. result.x = lm.m[12];
  81514. result.y = lm.m[13];
  81515. result.z = lm.m[14];
  81516. }
  81517. else {
  81518. var wm = null;
  81519. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81520. if (mesh) {
  81521. wm = mesh.getWorldMatrix();
  81522. }
  81523. this._skeleton.computeAbsoluteTransforms();
  81524. var tmat = Bone._tmpMats[0];
  81525. if (mesh && wm) {
  81526. tmat.copyFrom(this.getAbsoluteTransform());
  81527. tmat.multiplyToRef(wm, tmat);
  81528. }
  81529. else {
  81530. tmat = this.getAbsoluteTransform();
  81531. }
  81532. result.x = tmat.m[12];
  81533. result.y = tmat.m[13];
  81534. result.z = tmat.m[14];
  81535. }
  81536. };
  81537. /**
  81538. * Get the absolute position of the bone (world space)
  81539. * @param mesh The mesh that this bone is attached to
  81540. * @returns The absolute position of the bone
  81541. */
  81542. Bone.prototype.getAbsolutePosition = function (mesh) {
  81543. if (mesh === void 0) { mesh = null; }
  81544. var pos = BABYLON.Vector3.Zero();
  81545. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  81546. return pos;
  81547. };
  81548. /**
  81549. * Copy the absolute position of the bone (world space) to the result param
  81550. * @param mesh The mesh that this bone is attached to
  81551. * @param result The vector3 to copy the absolute position to
  81552. */
  81553. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  81554. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  81555. };
  81556. /**
  81557. * Compute the absolute transforms of this bone and its children
  81558. */
  81559. Bone.prototype.computeAbsoluteTransforms = function () {
  81560. this._compose();
  81561. if (this._parent) {
  81562. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  81563. }
  81564. else {
  81565. this._absoluteTransform.copyFrom(this._localMatrix);
  81566. var poseMatrix = this._skeleton.getPoseMatrix();
  81567. if (poseMatrix) {
  81568. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  81569. }
  81570. }
  81571. var children = this.children;
  81572. var len = children.length;
  81573. for (var i = 0; i < len; i++) {
  81574. children[i].computeAbsoluteTransforms();
  81575. }
  81576. };
  81577. /**
  81578. * Get the world direction from an axis that is in the local space of the bone
  81579. * @param localAxis The local direction that is used to compute the world direction
  81580. * @param mesh The mesh that this bone is attached to
  81581. * @returns The world direction
  81582. */
  81583. Bone.prototype.getDirection = function (localAxis, mesh) {
  81584. if (mesh === void 0) { mesh = null; }
  81585. var result = BABYLON.Vector3.Zero();
  81586. this.getDirectionToRef(localAxis, mesh, result);
  81587. return result;
  81588. };
  81589. /**
  81590. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  81591. * @param localAxis The local direction that is used to compute the world direction
  81592. * @param mesh The mesh that this bone is attached to
  81593. * @param result The vector3 that the world direction will be copied to
  81594. */
  81595. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  81596. if (mesh === void 0) { mesh = null; }
  81597. var wm = null;
  81598. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81599. if (mesh) {
  81600. wm = mesh.getWorldMatrix();
  81601. }
  81602. this._skeleton.computeAbsoluteTransforms();
  81603. var mat = Bone._tmpMats[0];
  81604. mat.copyFrom(this.getAbsoluteTransform());
  81605. if (mesh && wm) {
  81606. mat.multiplyToRef(wm, mat);
  81607. }
  81608. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  81609. result.normalize();
  81610. };
  81611. /**
  81612. * Get the euler rotation of the bone in local or world space
  81613. * @param space The space that the rotation should be in
  81614. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81615. * @returns The euler rotation
  81616. */
  81617. Bone.prototype.getRotation = function (space, mesh) {
  81618. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81619. if (mesh === void 0) { mesh = null; }
  81620. var result = BABYLON.Vector3.Zero();
  81621. this.getRotationToRef(space, mesh, result);
  81622. return result;
  81623. };
  81624. /**
  81625. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  81626. * @param space The space that the rotation should be in
  81627. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81628. * @param result The vector3 that the rotation should be copied to
  81629. */
  81630. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  81631. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81632. if (mesh === void 0) { mesh = null; }
  81633. var quat = Bone._tmpQuat;
  81634. this.getRotationQuaternionToRef(space, mesh, quat);
  81635. quat.toEulerAnglesToRef(result);
  81636. };
  81637. /**
  81638. * Get the quaternion rotation of the bone in either local or world space
  81639. * @param space The space that the rotation should be in
  81640. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81641. * @returns The quaternion rotation
  81642. */
  81643. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  81644. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81645. if (mesh === void 0) { mesh = null; }
  81646. var result = BABYLON.Quaternion.Identity();
  81647. this.getRotationQuaternionToRef(space, mesh, result);
  81648. return result;
  81649. };
  81650. /**
  81651. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  81652. * @param space The space that the rotation should be in
  81653. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81654. * @param result The quaternion that the rotation should be copied to
  81655. */
  81656. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  81657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81658. if (mesh === void 0) { mesh = null; }
  81659. if (space == BABYLON.Space.LOCAL) {
  81660. this._decompose();
  81661. result.copyFrom(this._localRotation);
  81662. }
  81663. else {
  81664. var mat = Bone._tmpMats[0];
  81665. var amat = this.getAbsoluteTransform();
  81666. if (mesh) {
  81667. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81668. }
  81669. else {
  81670. mat.copyFrom(amat);
  81671. }
  81672. mat.m[0] *= this._scalingDeterminant;
  81673. mat.m[1] *= this._scalingDeterminant;
  81674. mat.m[2] *= this._scalingDeterminant;
  81675. mat.decompose(undefined, result, undefined);
  81676. }
  81677. };
  81678. /**
  81679. * Get the rotation matrix of the bone in local or world space
  81680. * @param space The space that the rotation should be in
  81681. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81682. * @returns The rotation matrix
  81683. */
  81684. Bone.prototype.getRotationMatrix = function (space, mesh) {
  81685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81686. var result = BABYLON.Matrix.Identity();
  81687. this.getRotationMatrixToRef(space, mesh, result);
  81688. return result;
  81689. };
  81690. /**
  81691. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  81692. * @param space The space that the rotation should be in
  81693. * @param mesh The mesh that this bone is attached to. This is only used in world space
  81694. * @param result The quaternion that the rotation should be copied to
  81695. */
  81696. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  81697. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  81698. if (space == BABYLON.Space.LOCAL) {
  81699. this.getLocalMatrix().getRotationMatrixToRef(result);
  81700. }
  81701. else {
  81702. var mat = Bone._tmpMats[0];
  81703. var amat = this.getAbsoluteTransform();
  81704. if (mesh) {
  81705. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  81706. }
  81707. else {
  81708. mat.copyFrom(amat);
  81709. }
  81710. mat.m[0] *= this._scalingDeterminant;
  81711. mat.m[1] *= this._scalingDeterminant;
  81712. mat.m[2] *= this._scalingDeterminant;
  81713. mat.getRotationMatrixToRef(result);
  81714. }
  81715. };
  81716. /**
  81717. * Get the world position of a point that is in the local space of the bone
  81718. * @param position The local position
  81719. * @param mesh The mesh that this bone is attached to
  81720. * @returns The world position
  81721. */
  81722. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  81723. if (mesh === void 0) { mesh = null; }
  81724. var result = BABYLON.Vector3.Zero();
  81725. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  81726. return result;
  81727. };
  81728. /**
  81729. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  81730. * @param position The local position
  81731. * @param mesh The mesh that this bone is attached to
  81732. * @param result The vector3 that the world position should be copied to
  81733. */
  81734. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  81735. if (mesh === void 0) { mesh = null; }
  81736. var wm = null;
  81737. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81738. if (mesh) {
  81739. wm = mesh.getWorldMatrix();
  81740. }
  81741. this._skeleton.computeAbsoluteTransforms();
  81742. var tmat = Bone._tmpMats[0];
  81743. if (mesh && wm) {
  81744. tmat.copyFrom(this.getAbsoluteTransform());
  81745. tmat.multiplyToRef(wm, tmat);
  81746. }
  81747. else {
  81748. tmat = this.getAbsoluteTransform();
  81749. }
  81750. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81751. };
  81752. /**
  81753. * Get the local position of a point that is in world space
  81754. * @param position The world position
  81755. * @param mesh The mesh that this bone is attached to
  81756. * @returns The local position
  81757. */
  81758. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  81759. if (mesh === void 0) { mesh = null; }
  81760. var result = BABYLON.Vector3.Zero();
  81761. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  81762. return result;
  81763. };
  81764. /**
  81765. * Get the local position of a point that is in world space and copy it to the result param
  81766. * @param position The world position
  81767. * @param mesh The mesh that this bone is attached to
  81768. * @param result The vector3 that the local position should be copied to
  81769. */
  81770. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  81771. if (mesh === void 0) { mesh = null; }
  81772. var wm = null;
  81773. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  81774. if (mesh) {
  81775. wm = mesh.getWorldMatrix();
  81776. }
  81777. this._skeleton.computeAbsoluteTransforms();
  81778. var tmat = Bone._tmpMats[0];
  81779. tmat.copyFrom(this.getAbsoluteTransform());
  81780. if (mesh && wm) {
  81781. tmat.multiplyToRef(wm, tmat);
  81782. }
  81783. tmat.invert();
  81784. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  81785. };
  81786. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81787. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  81788. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81789. return Bone;
  81790. }(BABYLON.Node));
  81791. BABYLON.Bone = Bone;
  81792. })(BABYLON || (BABYLON = {}));
  81793. //# sourceMappingURL=babylon.bone.js.map
  81794. var BABYLON;
  81795. (function (BABYLON) {
  81796. /**
  81797. * Class used to apply inverse kinematics to bones
  81798. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  81799. */
  81800. var BoneIKController = /** @class */ (function () {
  81801. /**
  81802. * Creates a new BoneIKController
  81803. * @param mesh defines the mesh to control
  81804. * @param bone defines the bone to control
  81805. * @param options defines options to set up the controller
  81806. */
  81807. function BoneIKController(mesh, bone, options) {
  81808. /**
  81809. * Gets or sets the target position
  81810. */
  81811. this.targetPosition = BABYLON.Vector3.Zero();
  81812. /**
  81813. * Gets or sets the pole target position
  81814. */
  81815. this.poleTargetPosition = BABYLON.Vector3.Zero();
  81816. /**
  81817. * Gets or sets the pole target local offset
  81818. */
  81819. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  81820. /**
  81821. * Gets or sets the pole angle
  81822. */
  81823. this.poleAngle = 0;
  81824. /**
  81825. * 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)
  81826. */
  81827. this.slerpAmount = 1;
  81828. this._bone1Quat = BABYLON.Quaternion.Identity();
  81829. this._bone1Mat = BABYLON.Matrix.Identity();
  81830. this._bone2Ang = Math.PI;
  81831. this._maxAngle = Math.PI;
  81832. this._rightHandedSystem = false;
  81833. this._bendAxis = BABYLON.Vector3.Right();
  81834. this._slerping = false;
  81835. this._adjustRoll = 0;
  81836. this._bone2 = bone;
  81837. this._bone1 = bone.getParent();
  81838. if (!this._bone1) {
  81839. return;
  81840. }
  81841. this.mesh = mesh;
  81842. var bonePos = bone.getPosition();
  81843. if (bone.getAbsoluteTransform().determinant() > 0) {
  81844. this._rightHandedSystem = true;
  81845. this._bendAxis.x = 0;
  81846. this._bendAxis.y = 0;
  81847. this._bendAxis.z = -1;
  81848. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  81849. this._adjustRoll = Math.PI * .5;
  81850. this._bendAxis.z = 1;
  81851. }
  81852. }
  81853. if (this._bone1.length) {
  81854. var boneScale1 = this._bone1.getScale();
  81855. var boneScale2 = this._bone2.getScale();
  81856. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  81857. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  81858. }
  81859. else if (this._bone1.children[0]) {
  81860. mesh.computeWorldMatrix(true);
  81861. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  81862. var pos2 = this._bone2.getAbsolutePosition(mesh);
  81863. var pos3 = this._bone1.getAbsolutePosition(mesh);
  81864. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  81865. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  81866. }
  81867. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  81868. this.maxAngle = Math.PI;
  81869. if (options) {
  81870. if (options.targetMesh) {
  81871. this.targetMesh = options.targetMesh;
  81872. this.targetMesh.computeWorldMatrix(true);
  81873. }
  81874. if (options.poleTargetMesh) {
  81875. this.poleTargetMesh = options.poleTargetMesh;
  81876. this.poleTargetMesh.computeWorldMatrix(true);
  81877. }
  81878. else if (options.poleTargetBone) {
  81879. this.poleTargetBone = options.poleTargetBone;
  81880. }
  81881. else if (this._bone1.getParent()) {
  81882. this.poleTargetBone = this._bone1.getParent();
  81883. }
  81884. if (options.poleTargetLocalOffset) {
  81885. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  81886. }
  81887. if (options.poleAngle) {
  81888. this.poleAngle = options.poleAngle;
  81889. }
  81890. if (options.bendAxis) {
  81891. this._bendAxis.copyFrom(options.bendAxis);
  81892. }
  81893. if (options.maxAngle) {
  81894. this.maxAngle = options.maxAngle;
  81895. }
  81896. if (options.slerpAmount) {
  81897. this.slerpAmount = options.slerpAmount;
  81898. }
  81899. }
  81900. }
  81901. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  81902. /**
  81903. * Gets or sets maximum allowed angle
  81904. */
  81905. get: function () {
  81906. return this._maxAngle;
  81907. },
  81908. set: function (value) {
  81909. this._setMaxAngle(value);
  81910. },
  81911. enumerable: true,
  81912. configurable: true
  81913. });
  81914. BoneIKController.prototype._setMaxAngle = function (ang) {
  81915. if (ang < 0) {
  81916. ang = 0;
  81917. }
  81918. if (ang > Math.PI || ang == undefined) {
  81919. ang = Math.PI;
  81920. }
  81921. this._maxAngle = ang;
  81922. var a = this._bone1Length;
  81923. var b = this._bone2Length;
  81924. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  81925. };
  81926. /**
  81927. * Force the controller to update the bones
  81928. */
  81929. BoneIKController.prototype.update = function () {
  81930. var bone1 = this._bone1;
  81931. if (!bone1) {
  81932. return;
  81933. }
  81934. var target = this.targetPosition;
  81935. var poleTarget = this.poleTargetPosition;
  81936. var mat1 = BoneIKController._tmpMats[0];
  81937. var mat2 = BoneIKController._tmpMats[1];
  81938. if (this.targetMesh) {
  81939. target.copyFrom(this.targetMesh.getAbsolutePosition());
  81940. }
  81941. if (this.poleTargetBone) {
  81942. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  81943. }
  81944. else if (this.poleTargetMesh) {
  81945. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  81946. }
  81947. var bonePos = BoneIKController._tmpVecs[0];
  81948. var zaxis = BoneIKController._tmpVecs[1];
  81949. var xaxis = BoneIKController._tmpVecs[2];
  81950. var yaxis = BoneIKController._tmpVecs[3];
  81951. var upAxis = BoneIKController._tmpVecs[4];
  81952. var _tmpQuat = BoneIKController._tmpQuat;
  81953. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  81954. poleTarget.subtractToRef(bonePos, upAxis);
  81955. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  81956. upAxis.y = 1;
  81957. }
  81958. else {
  81959. upAxis.normalize();
  81960. }
  81961. target.subtractToRef(bonePos, yaxis);
  81962. yaxis.normalize();
  81963. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  81964. zaxis.normalize();
  81965. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  81966. xaxis.normalize();
  81967. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  81968. var a = this._bone1Length;
  81969. var b = this._bone2Length;
  81970. var c = BABYLON.Vector3.Distance(bonePos, target);
  81971. if (this._maxReach > 0) {
  81972. c = Math.min(this._maxReach, c);
  81973. }
  81974. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  81975. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  81976. if (acosa > 1) {
  81977. acosa = 1;
  81978. }
  81979. if (acosb > 1) {
  81980. acosb = 1;
  81981. }
  81982. if (acosa < -1) {
  81983. acosa = -1;
  81984. }
  81985. if (acosb < -1) {
  81986. acosb = -1;
  81987. }
  81988. var angA = Math.acos(acosa);
  81989. var angB = Math.acos(acosb);
  81990. var angC = -angA - angB;
  81991. if (this._rightHandedSystem) {
  81992. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  81993. mat2.multiplyToRef(mat1, mat1);
  81994. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  81995. mat2.multiplyToRef(mat1, mat1);
  81996. }
  81997. else {
  81998. var _tmpVec = BoneIKController._tmpVecs[5];
  81999. _tmpVec.copyFrom(this._bendAxis);
  82000. _tmpVec.x *= -1;
  82001. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  82002. mat2.multiplyToRef(mat1, mat1);
  82003. }
  82004. if (this.poleAngle) {
  82005. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  82006. mat1.multiplyToRef(mat2, mat1);
  82007. }
  82008. if (this._bone1) {
  82009. if (this.slerpAmount < 1) {
  82010. if (!this._slerping) {
  82011. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  82012. }
  82013. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  82014. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  82015. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  82016. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  82017. this._slerping = true;
  82018. }
  82019. else {
  82020. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  82021. this._bone1Mat.copyFrom(mat1);
  82022. this._slerping = false;
  82023. }
  82024. }
  82025. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  82026. this._bone2Ang = angC;
  82027. };
  82028. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82029. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  82030. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82031. return BoneIKController;
  82032. }());
  82033. BABYLON.BoneIKController = BoneIKController;
  82034. })(BABYLON || (BABYLON = {}));
  82035. //# sourceMappingURL=babylon.boneIKController.js.map
  82036. var BABYLON;
  82037. (function (BABYLON) {
  82038. /**
  82039. * Class used to make a bone look toward a point in space
  82040. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  82041. */
  82042. var BoneLookController = /** @class */ (function () {
  82043. /**
  82044. * Create a BoneLookController
  82045. * @param mesh the mesh that the bone belongs to
  82046. * @param bone the bone that will be looking to the target
  82047. * @param target the target Vector3 to look at
  82048. * @param settings optional settings:
  82049. * * maxYaw: the maximum angle the bone will yaw to
  82050. * * minYaw: the minimum angle the bone will yaw to
  82051. * * maxPitch: the maximum angle the bone will pitch to
  82052. * * minPitch: the minimum angle the bone will yaw to
  82053. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  82054. * * upAxis: the up axis of the coordinate system
  82055. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  82056. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  82057. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  82058. * * adjustYaw: used to make an adjustment to the yaw of the bone
  82059. * * adjustPitch: used to make an adjustment to the pitch of the bone
  82060. * * adjustRoll: used to make an adjustment to the roll of the bone
  82061. **/
  82062. function BoneLookController(mesh, bone, target, options) {
  82063. /**
  82064. * The up axis of the coordinate system that is used when the bone is rotated
  82065. */
  82066. this.upAxis = BABYLON.Vector3.Up();
  82067. /**
  82068. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  82069. */
  82070. this.upAxisSpace = BABYLON.Space.LOCAL;
  82071. /**
  82072. * Used to make an adjustment to the yaw of the bone
  82073. */
  82074. this.adjustYaw = 0;
  82075. /**
  82076. * Used to make an adjustment to the pitch of the bone
  82077. */
  82078. this.adjustPitch = 0;
  82079. /**
  82080. * Used to make an adjustment to the roll of the bone
  82081. */
  82082. this.adjustRoll = 0;
  82083. /**
  82084. * 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)
  82085. */
  82086. this.slerpAmount = 1;
  82087. this._boneQuat = BABYLON.Quaternion.Identity();
  82088. this._slerping = false;
  82089. this._firstFrameSkipped = false;
  82090. this._fowardAxis = BABYLON.Vector3.Forward();
  82091. this.mesh = mesh;
  82092. this.bone = bone;
  82093. this.target = target;
  82094. if (options) {
  82095. if (options.adjustYaw) {
  82096. this.adjustYaw = options.adjustYaw;
  82097. }
  82098. if (options.adjustPitch) {
  82099. this.adjustPitch = options.adjustPitch;
  82100. }
  82101. if (options.adjustRoll) {
  82102. this.adjustRoll = options.adjustRoll;
  82103. }
  82104. if (options.maxYaw != null) {
  82105. this.maxYaw = options.maxYaw;
  82106. }
  82107. else {
  82108. this.maxYaw = Math.PI;
  82109. }
  82110. if (options.minYaw != null) {
  82111. this.minYaw = options.minYaw;
  82112. }
  82113. else {
  82114. this.minYaw = -Math.PI;
  82115. }
  82116. if (options.maxPitch != null) {
  82117. this.maxPitch = options.maxPitch;
  82118. }
  82119. else {
  82120. this.maxPitch = Math.PI;
  82121. }
  82122. if (options.minPitch != null) {
  82123. this.minPitch = options.minPitch;
  82124. }
  82125. else {
  82126. this.minPitch = -Math.PI;
  82127. }
  82128. if (options.slerpAmount != null) {
  82129. this.slerpAmount = options.slerpAmount;
  82130. }
  82131. if (options.upAxis != null) {
  82132. this.upAxis = options.upAxis;
  82133. }
  82134. if (options.upAxisSpace != null) {
  82135. this.upAxisSpace = options.upAxisSpace;
  82136. }
  82137. if (options.yawAxis != null || options.pitchAxis != null) {
  82138. var newYawAxis = BABYLON.Axis.Y;
  82139. var newPitchAxis = BABYLON.Axis.X;
  82140. if (options.yawAxis != null) {
  82141. newYawAxis = options.yawAxis.clone();
  82142. newYawAxis.normalize();
  82143. }
  82144. if (options.pitchAxis != null) {
  82145. newPitchAxis = options.pitchAxis.clone();
  82146. newPitchAxis.normalize();
  82147. }
  82148. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  82149. this._transformYawPitch = BABYLON.Matrix.Identity();
  82150. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  82151. this._transformYawPitchInv = this._transformYawPitch.clone();
  82152. this._transformYawPitch.invert();
  82153. }
  82154. }
  82155. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  82156. this.upAxisSpace = BABYLON.Space.LOCAL;
  82157. }
  82158. }
  82159. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  82160. /**
  82161. * Gets or sets the minimum yaw angle that the bone can look to
  82162. */
  82163. get: function () {
  82164. return this._minYaw;
  82165. },
  82166. set: function (value) {
  82167. this._minYaw = value;
  82168. this._minYawSin = Math.sin(value);
  82169. this._minYawCos = Math.cos(value);
  82170. if (this._maxYaw != null) {
  82171. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82172. this._yawRange = this._maxYaw - this._minYaw;
  82173. }
  82174. },
  82175. enumerable: true,
  82176. configurable: true
  82177. });
  82178. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  82179. /**
  82180. * Gets or sets the maximum yaw angle that the bone can look to
  82181. */
  82182. get: function () {
  82183. return this._maxYaw;
  82184. },
  82185. set: function (value) {
  82186. this._maxYaw = value;
  82187. this._maxYawSin = Math.sin(value);
  82188. this._maxYawCos = Math.cos(value);
  82189. if (this._minYaw != null) {
  82190. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  82191. this._yawRange = this._maxYaw - this._minYaw;
  82192. }
  82193. },
  82194. enumerable: true,
  82195. configurable: true
  82196. });
  82197. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  82198. /**
  82199. * Gets or sets the minimum pitch angle that the bone can look to
  82200. */
  82201. get: function () {
  82202. return this._minPitch;
  82203. },
  82204. set: function (value) {
  82205. this._minPitch = value;
  82206. this._minPitchTan = Math.tan(value);
  82207. },
  82208. enumerable: true,
  82209. configurable: true
  82210. });
  82211. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  82212. /**
  82213. * Gets or sets the maximum pitch angle that the bone can look to
  82214. */
  82215. get: function () {
  82216. return this._maxPitch;
  82217. },
  82218. set: function (value) {
  82219. this._maxPitch = value;
  82220. this._maxPitchTan = Math.tan(value);
  82221. },
  82222. enumerable: true,
  82223. configurable: true
  82224. });
  82225. /**
  82226. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  82227. */
  82228. BoneLookController.prototype.update = function () {
  82229. //skip the first frame when slerping so that the mesh rotation is correct
  82230. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  82231. this._firstFrameSkipped = true;
  82232. return;
  82233. }
  82234. var bone = this.bone;
  82235. var bonePos = BoneLookController._tmpVecs[0];
  82236. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  82237. var target = this.target;
  82238. var _tmpMat1 = BoneLookController._tmpMats[0];
  82239. var _tmpMat2 = BoneLookController._tmpMats[1];
  82240. var mesh = this.mesh;
  82241. var parentBone = bone.getParent();
  82242. var upAxis = BoneLookController._tmpVecs[1];
  82243. upAxis.copyFrom(this.upAxis);
  82244. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  82245. if (this._transformYawPitch) {
  82246. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  82247. }
  82248. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  82249. }
  82250. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  82251. mesh.getDirectionToRef(upAxis, upAxis);
  82252. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  82253. upAxis.normalize();
  82254. }
  82255. }
  82256. var checkYaw = false;
  82257. var checkPitch = false;
  82258. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  82259. checkYaw = true;
  82260. }
  82261. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  82262. checkPitch = true;
  82263. }
  82264. if (checkYaw || checkPitch) {
  82265. var spaceMat = BoneLookController._tmpMats[2];
  82266. var spaceMatInv = BoneLookController._tmpMats[3];
  82267. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  82268. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  82269. }
  82270. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  82271. spaceMat.copyFrom(mesh.getWorldMatrix());
  82272. }
  82273. else {
  82274. var forwardAxis = BoneLookController._tmpVecs[2];
  82275. forwardAxis.copyFrom(this._fowardAxis);
  82276. if (this._transformYawPitch) {
  82277. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  82278. }
  82279. if (parentBone) {
  82280. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  82281. }
  82282. else {
  82283. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  82284. }
  82285. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  82286. rightAxis.normalize();
  82287. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  82288. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  82289. }
  82290. spaceMat.invertToRef(spaceMatInv);
  82291. var xzlen = null;
  82292. if (checkPitch) {
  82293. var localTarget = BoneLookController._tmpVecs[3];
  82294. target.subtractToRef(bonePos, localTarget);
  82295. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82296. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82297. var pitch = Math.atan2(localTarget.y, xzlen);
  82298. var newPitch = pitch;
  82299. if (pitch > this._maxPitch) {
  82300. localTarget.y = this._maxPitchTan * xzlen;
  82301. newPitch = this._maxPitch;
  82302. }
  82303. else if (pitch < this._minPitch) {
  82304. localTarget.y = this._minPitchTan * xzlen;
  82305. newPitch = this._minPitch;
  82306. }
  82307. if (pitch != newPitch) {
  82308. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82309. localTarget.addInPlace(bonePos);
  82310. target = localTarget;
  82311. }
  82312. }
  82313. if (checkYaw) {
  82314. var localTarget = BoneLookController._tmpVecs[4];
  82315. target.subtractToRef(bonePos, localTarget);
  82316. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  82317. var yaw = Math.atan2(localTarget.x, localTarget.z);
  82318. var newYaw = yaw;
  82319. if (yaw > this._maxYaw || yaw < this._minYaw) {
  82320. if (xzlen == null) {
  82321. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82322. }
  82323. if (this._yawRange > Math.PI) {
  82324. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  82325. localTarget.z = this._maxYawCos * xzlen;
  82326. localTarget.x = this._maxYawSin * xzlen;
  82327. newYaw = this._maxYaw;
  82328. }
  82329. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  82330. localTarget.z = this._minYawCos * xzlen;
  82331. localTarget.x = this._minYawSin * xzlen;
  82332. newYaw = this._minYaw;
  82333. }
  82334. }
  82335. else {
  82336. if (yaw > this._maxYaw) {
  82337. localTarget.z = this._maxYawCos * xzlen;
  82338. localTarget.x = this._maxYawSin * xzlen;
  82339. newYaw = this._maxYaw;
  82340. }
  82341. else if (yaw < this._minYaw) {
  82342. localTarget.z = this._minYawCos * xzlen;
  82343. localTarget.x = this._minYawSin * xzlen;
  82344. newYaw = this._minYaw;
  82345. }
  82346. }
  82347. }
  82348. if (this._slerping && this._yawRange > Math.PI) {
  82349. //are we going to be crossing into the min/max region?
  82350. var boneFwd = BoneLookController._tmpVecs[8];
  82351. boneFwd.copyFrom(BABYLON.Axis.Z);
  82352. if (this._transformYawPitch) {
  82353. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  82354. }
  82355. var boneRotMat = BoneLookController._tmpMats[4];
  82356. this._boneQuat.toRotationMatrix(boneRotMat);
  82357. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  82358. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  82359. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  82360. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  82361. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  82362. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  82363. if (angBtwTar > angBtwMidYaw) {
  82364. if (xzlen == null) {
  82365. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  82366. }
  82367. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  82368. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  82369. if (angBtwMin < angBtwMax) {
  82370. newYaw = boneYaw + Math.PI * .75;
  82371. localTarget.z = Math.cos(newYaw) * xzlen;
  82372. localTarget.x = Math.sin(newYaw) * xzlen;
  82373. }
  82374. else {
  82375. newYaw = boneYaw - Math.PI * .75;
  82376. localTarget.z = Math.cos(newYaw) * xzlen;
  82377. localTarget.x = Math.sin(newYaw) * xzlen;
  82378. }
  82379. }
  82380. }
  82381. if (yaw != newYaw) {
  82382. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  82383. localTarget.addInPlace(bonePos);
  82384. target = localTarget;
  82385. }
  82386. }
  82387. }
  82388. var zaxis = BoneLookController._tmpVecs[5];
  82389. var xaxis = BoneLookController._tmpVecs[6];
  82390. var yaxis = BoneLookController._tmpVecs[7];
  82391. var _tmpQuat = BoneLookController._tmpQuat;
  82392. target.subtractToRef(bonePos, zaxis);
  82393. zaxis.normalize();
  82394. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  82395. xaxis.normalize();
  82396. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  82397. yaxis.normalize();
  82398. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  82399. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  82400. return;
  82401. }
  82402. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  82403. return;
  82404. }
  82405. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  82406. return;
  82407. }
  82408. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  82409. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  82410. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  82411. }
  82412. if (this.slerpAmount < 1) {
  82413. if (!this._slerping) {
  82414. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  82415. }
  82416. if (this._transformYawPitch) {
  82417. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82418. }
  82419. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  82420. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  82421. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  82422. this._slerping = true;
  82423. }
  82424. else {
  82425. if (this._transformYawPitch) {
  82426. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  82427. }
  82428. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  82429. this._slerping = false;
  82430. }
  82431. };
  82432. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  82433. var angDiff = ang2 - ang1;
  82434. angDiff %= Math.PI * 2;
  82435. if (angDiff > Math.PI) {
  82436. angDiff -= Math.PI * 2;
  82437. }
  82438. else if (angDiff < -Math.PI) {
  82439. angDiff += Math.PI * 2;
  82440. }
  82441. return angDiff;
  82442. };
  82443. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  82444. ang1 %= (2 * Math.PI);
  82445. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82446. ang2 %= (2 * Math.PI);
  82447. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82448. var ab = 0;
  82449. if (ang1 < ang2) {
  82450. ab = ang2 - ang1;
  82451. }
  82452. else {
  82453. ab = ang1 - ang2;
  82454. }
  82455. if (ab > Math.PI) {
  82456. ab = Math.PI * 2 - ab;
  82457. }
  82458. return ab;
  82459. };
  82460. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  82461. ang %= (2 * Math.PI);
  82462. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  82463. ang1 %= (2 * Math.PI);
  82464. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  82465. ang2 %= (2 * Math.PI);
  82466. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  82467. if (ang1 < ang2) {
  82468. if (ang > ang1 && ang < ang2) {
  82469. return true;
  82470. }
  82471. }
  82472. else {
  82473. if (ang > ang2 && ang < ang1) {
  82474. return true;
  82475. }
  82476. }
  82477. return false;
  82478. };
  82479. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82480. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  82481. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  82482. return BoneLookController;
  82483. }());
  82484. BABYLON.BoneLookController = BoneLookController;
  82485. })(BABYLON || (BABYLON = {}));
  82486. //# sourceMappingURL=babylon.boneLookController.js.map
  82487. var BABYLON;
  82488. (function (BABYLON) {
  82489. /**
  82490. * Class used to handle skinning animations
  82491. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82492. */
  82493. var Skeleton = /** @class */ (function () {
  82494. /**
  82495. * Creates a new skeleton
  82496. * @param name defines the skeleton name
  82497. * @param id defines the skeleton Id
  82498. * @param scene defines the hosting scene
  82499. */
  82500. function Skeleton(
  82501. /** defines the skeleton name */
  82502. name,
  82503. /** defines the skeleton Id */
  82504. id, scene) {
  82505. this.name = name;
  82506. this.id = id;
  82507. /**
  82508. * Gets the list of child bones
  82509. */
  82510. this.bones = new Array();
  82511. /**
  82512. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  82513. */
  82514. this.needInitialSkinMatrix = false;
  82515. this._isDirty = true;
  82516. this._meshesWithPoseMatrix = new Array();
  82517. this._identity = BABYLON.Matrix.Identity();
  82518. this._ranges = {};
  82519. this._lastAbsoluteTransformsUpdateId = -1;
  82520. /**
  82521. * Specifies if the skeleton should be serialized
  82522. */
  82523. this.doNotSerialize = false;
  82524. this._animationPropertiesOverride = null;
  82525. // Events
  82526. /**
  82527. * An observable triggered before computing the skeleton's matrices
  82528. */
  82529. this.onBeforeComputeObservable = new BABYLON.Observable();
  82530. this.bones = [];
  82531. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82532. scene.skeletons.push(this);
  82533. //make sure it will recalculate the matrix next time prepare is called.
  82534. this._isDirty = true;
  82535. }
  82536. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  82537. /**
  82538. * Gets or sets the animation properties override
  82539. */
  82540. get: function () {
  82541. if (!this._animationPropertiesOverride) {
  82542. return this._scene.animationPropertiesOverride;
  82543. }
  82544. return this._animationPropertiesOverride;
  82545. },
  82546. set: function (value) {
  82547. this._animationPropertiesOverride = value;
  82548. },
  82549. enumerable: true,
  82550. configurable: true
  82551. });
  82552. // Members
  82553. /**
  82554. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  82555. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  82556. * @returns a Float32Array containing matrices data
  82557. */
  82558. Skeleton.prototype.getTransformMatrices = function (mesh) {
  82559. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  82560. return mesh._bonesTransformMatrices;
  82561. }
  82562. if (!this._transformMatrices) {
  82563. this.prepare();
  82564. }
  82565. return this._transformMatrices;
  82566. };
  82567. /**
  82568. * Gets the current hosting scene
  82569. * @returns a scene object
  82570. */
  82571. Skeleton.prototype.getScene = function () {
  82572. return this._scene;
  82573. };
  82574. // Methods
  82575. /**
  82576. * Gets a string representing the current skeleton data
  82577. * @param fullDetails defines a boolean indicating if we want a verbose version
  82578. * @returns a string representing the current skeleton data
  82579. */
  82580. Skeleton.prototype.toString = function (fullDetails) {
  82581. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  82582. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  82583. if (fullDetails) {
  82584. ret += ", Ranges: {";
  82585. var first = true;
  82586. for (var name_1 in this._ranges) {
  82587. if (first) {
  82588. ret += ", ";
  82589. first = false;
  82590. }
  82591. ret += name_1;
  82592. }
  82593. ret += "}";
  82594. }
  82595. return ret;
  82596. };
  82597. /**
  82598. * Get bone's index searching by name
  82599. * @param name defines bone's name to search for
  82600. * @return the indice of the bone. Returns -1 if not found
  82601. */
  82602. Skeleton.prototype.getBoneIndexByName = function (name) {
  82603. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  82604. if (this.bones[boneIndex].name === name) {
  82605. return boneIndex;
  82606. }
  82607. }
  82608. return -1;
  82609. };
  82610. /**
  82611. * Creater a new animation range
  82612. * @param name defines the name of the range
  82613. * @param from defines the start key
  82614. * @param to defines the end key
  82615. */
  82616. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  82617. // check name not already in use
  82618. if (!this._ranges[name]) {
  82619. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  82620. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82621. if (this.bones[i].animations[0]) {
  82622. this.bones[i].animations[0].createRange(name, from, to);
  82623. }
  82624. }
  82625. }
  82626. };
  82627. /**
  82628. * Delete a specific animation range
  82629. * @param name defines the name of the range
  82630. * @param deleteFrames defines if frames must be removed as well
  82631. */
  82632. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  82633. if (deleteFrames === void 0) { deleteFrames = true; }
  82634. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82635. if (this.bones[i].animations[0]) {
  82636. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  82637. }
  82638. }
  82639. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  82640. };
  82641. /**
  82642. * Gets a specific animation range
  82643. * @param name defines the name of the range to look for
  82644. * @returns the requested animation range or null if not found
  82645. */
  82646. Skeleton.prototype.getAnimationRange = function (name) {
  82647. return this._ranges[name];
  82648. };
  82649. /**
  82650. * Gets the list of all animation ranges defined on this skeleton
  82651. * @returns an array
  82652. */
  82653. Skeleton.prototype.getAnimationRanges = function () {
  82654. var animationRanges = [];
  82655. var name;
  82656. var i = 0;
  82657. for (name in this._ranges) {
  82658. animationRanges[i] = this._ranges[name];
  82659. i++;
  82660. }
  82661. return animationRanges;
  82662. };
  82663. /**
  82664. * Copy animation range from a source skeleton.
  82665. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  82666. * @param source defines the source skeleton
  82667. * @param name defines the name of the range to copy
  82668. * @param rescaleAsRequired defines if rescaling must be applied if required
  82669. * @returns true if operation was successful
  82670. */
  82671. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  82672. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82673. if (this._ranges[name] || !source.getAnimationRange(name)) {
  82674. return false;
  82675. }
  82676. var ret = true;
  82677. var frameOffset = this._getHighestAnimationFrame() + 1;
  82678. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  82679. var boneDict = {};
  82680. var sourceBones = source.bones;
  82681. var nBones;
  82682. var i;
  82683. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  82684. boneDict[sourceBones[i].name] = sourceBones[i];
  82685. }
  82686. if (this.bones.length !== sourceBones.length) {
  82687. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  82688. ret = false;
  82689. }
  82690. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  82691. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  82692. var boneName = this.bones[i].name;
  82693. var sourceBone = boneDict[boneName];
  82694. if (sourceBone) {
  82695. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  82696. }
  82697. else {
  82698. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  82699. ret = false;
  82700. }
  82701. }
  82702. // do not call createAnimationRange(), since it also is done to bones, which was already done
  82703. var range = source.getAnimationRange(name);
  82704. if (range) {
  82705. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  82706. }
  82707. return ret;
  82708. };
  82709. /**
  82710. * Forces the skeleton to go to rest pose
  82711. */
  82712. Skeleton.prototype.returnToRest = function () {
  82713. for (var index = 0; index < this.bones.length; index++) {
  82714. this.bones[index].returnToRest();
  82715. }
  82716. };
  82717. Skeleton.prototype._getHighestAnimationFrame = function () {
  82718. var ret = 0;
  82719. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  82720. if (this.bones[i].animations[0]) {
  82721. var highest = this.bones[i].animations[0].getHighestFrame();
  82722. if (ret < highest) {
  82723. ret = highest;
  82724. }
  82725. }
  82726. }
  82727. return ret;
  82728. };
  82729. /**
  82730. * Begin a specific animation range
  82731. * @param name defines the name of the range to start
  82732. * @param loop defines if looping must be turned on (false by default)
  82733. * @param speedRatio defines the speed ratio to apply (1 by default)
  82734. * @param onAnimationEnd defines a callback which will be called when animation will end
  82735. * @returns a new animatable
  82736. */
  82737. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  82738. var range = this.getAnimationRange(name);
  82739. if (!range) {
  82740. return null;
  82741. }
  82742. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  82743. };
  82744. /** @hidden */
  82745. Skeleton.prototype._markAsDirty = function () {
  82746. this._isDirty = true;
  82747. };
  82748. /** @hidden */
  82749. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  82750. this._meshesWithPoseMatrix.push(mesh);
  82751. };
  82752. /** @hidden */
  82753. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  82754. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  82755. if (index > -1) {
  82756. this._meshesWithPoseMatrix.splice(index, 1);
  82757. }
  82758. };
  82759. /** @hidden */
  82760. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  82761. this.onBeforeComputeObservable.notifyObservers(this);
  82762. for (var index = 0; index < this.bones.length; index++) {
  82763. var bone = this.bones[index];
  82764. var parentBone = bone.getParent();
  82765. if (parentBone) {
  82766. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  82767. }
  82768. else {
  82769. if (initialSkinMatrix) {
  82770. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  82771. }
  82772. else {
  82773. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  82774. }
  82775. }
  82776. if (bone._index !== -1) {
  82777. var mappedIndex = bone._index === null ? index : bone._index;
  82778. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  82779. }
  82780. }
  82781. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  82782. };
  82783. /**
  82784. * Build all resources required to render a skeleton
  82785. */
  82786. Skeleton.prototype.prepare = function () {
  82787. if (!this._isDirty) {
  82788. return;
  82789. }
  82790. if (this.needInitialSkinMatrix) {
  82791. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  82792. var mesh = this._meshesWithPoseMatrix[index];
  82793. var poseMatrix = mesh.getPoseMatrix();
  82794. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  82795. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82796. }
  82797. if (this._synchronizedWithMesh !== mesh) {
  82798. this._synchronizedWithMesh = mesh;
  82799. // Prepare bones
  82800. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  82801. var bone = this.bones[boneIndex];
  82802. if (!bone.getParent()) {
  82803. var matrix = bone.getBaseMatrix();
  82804. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  82805. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  82806. }
  82807. }
  82808. }
  82809. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  82810. }
  82811. }
  82812. else {
  82813. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  82814. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  82815. }
  82816. this._computeTransformMatrices(this._transformMatrices, null);
  82817. }
  82818. this._isDirty = false;
  82819. this._scene._activeBones.addCount(this.bones.length, false);
  82820. };
  82821. /**
  82822. * Gets the list of animatables currently running for this skeleton
  82823. * @returns an array of animatables
  82824. */
  82825. Skeleton.prototype.getAnimatables = function () {
  82826. if (!this._animatables || this._animatables.length !== this.bones.length) {
  82827. this._animatables = [];
  82828. for (var index = 0; index < this.bones.length; index++) {
  82829. this._animatables.push(this.bones[index]);
  82830. }
  82831. }
  82832. return this._animatables;
  82833. };
  82834. /**
  82835. * Clone the current skeleton
  82836. * @param name defines the name of the new skeleton
  82837. * @param id defines the id of the enw skeleton
  82838. * @returns the new skeleton
  82839. */
  82840. Skeleton.prototype.clone = function (name, id) {
  82841. var result = new Skeleton(name, id || name, this._scene);
  82842. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82843. for (var index = 0; index < this.bones.length; index++) {
  82844. var source = this.bones[index];
  82845. var parentBone = null;
  82846. var parent_1 = source.getParent();
  82847. if (parent_1) {
  82848. var parentIndex = this.bones.indexOf(parent_1);
  82849. parentBone = result.bones[parentIndex];
  82850. }
  82851. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  82852. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  82853. }
  82854. if (this._ranges) {
  82855. result._ranges = {};
  82856. for (var rangeName in this._ranges) {
  82857. var range = this._ranges[rangeName];
  82858. if (range) {
  82859. result._ranges[rangeName] = range.clone();
  82860. }
  82861. }
  82862. }
  82863. this._isDirty = true;
  82864. return result;
  82865. };
  82866. /**
  82867. * Enable animation blending for this skeleton
  82868. * @param blendingSpeed defines the blending speed to apply
  82869. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  82870. */
  82871. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  82872. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  82873. this.bones.forEach(function (bone) {
  82874. bone.animations.forEach(function (animation) {
  82875. animation.enableBlending = true;
  82876. animation.blendingSpeed = blendingSpeed;
  82877. });
  82878. });
  82879. };
  82880. /**
  82881. * Releases all resources associated with the current skeleton
  82882. */
  82883. Skeleton.prototype.dispose = function () {
  82884. this._meshesWithPoseMatrix = [];
  82885. // Animations
  82886. this.getScene().stopAnimation(this);
  82887. // Remove from scene
  82888. this.getScene().removeSkeleton(this);
  82889. };
  82890. /**
  82891. * Serialize the skeleton in a JSON object
  82892. * @returns a JSON object
  82893. */
  82894. Skeleton.prototype.serialize = function () {
  82895. var serializationObject = {};
  82896. serializationObject.name = this.name;
  82897. serializationObject.id = this.id;
  82898. if (this.dimensionsAtRest) {
  82899. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  82900. }
  82901. serializationObject.bones = [];
  82902. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  82903. for (var index = 0; index < this.bones.length; index++) {
  82904. var bone = this.bones[index];
  82905. var parent_2 = bone.getParent();
  82906. var serializedBone = {
  82907. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  82908. name: bone.name,
  82909. matrix: bone.getBaseMatrix().toArray(),
  82910. rest: bone.getRestPose().toArray()
  82911. };
  82912. serializationObject.bones.push(serializedBone);
  82913. if (bone.length) {
  82914. serializedBone.length = bone.length;
  82915. }
  82916. if (bone.metadata) {
  82917. serializedBone.metadata = bone.metadata;
  82918. }
  82919. if (bone.animations && bone.animations.length > 0) {
  82920. serializedBone.animation = bone.animations[0].serialize();
  82921. }
  82922. serializationObject.ranges = [];
  82923. for (var name in this._ranges) {
  82924. var source = this._ranges[name];
  82925. if (!source) {
  82926. continue;
  82927. }
  82928. var range = {};
  82929. range.name = name;
  82930. range.from = source.from;
  82931. range.to = source.to;
  82932. serializationObject.ranges.push(range);
  82933. }
  82934. }
  82935. return serializationObject;
  82936. };
  82937. /**
  82938. * Creates a new skeleton from serialized data
  82939. * @param parsedSkeleton defines the serialized data
  82940. * @param scene defines the hosting scene
  82941. * @returns a new skeleton
  82942. */
  82943. Skeleton.Parse = function (parsedSkeleton, scene) {
  82944. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  82945. if (parsedSkeleton.dimensionsAtRest) {
  82946. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  82947. }
  82948. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  82949. var index;
  82950. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  82951. var parsedBone = parsedSkeleton.bones[index];
  82952. var parentBone = null;
  82953. if (parsedBone.parentBoneIndex > -1) {
  82954. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  82955. }
  82956. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  82957. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  82958. if (parsedBone.length) {
  82959. bone.length = parsedBone.length;
  82960. }
  82961. if (parsedBone.metadata) {
  82962. bone.metadata = parsedBone.metadata;
  82963. }
  82964. if (parsedBone.animation) {
  82965. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  82966. }
  82967. }
  82968. // placed after bones, so createAnimationRange can cascade down
  82969. if (parsedSkeleton.ranges) {
  82970. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  82971. var data = parsedSkeleton.ranges[index];
  82972. skeleton.createAnimationRange(data.name, data.from, data.to);
  82973. }
  82974. }
  82975. return skeleton;
  82976. };
  82977. /**
  82978. * Compute all node absolute transforms
  82979. * @param forceUpdate defines if computation must be done even if cache is up to date
  82980. */
  82981. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  82982. if (forceUpdate === void 0) { forceUpdate = false; }
  82983. var renderId = this._scene.getRenderId();
  82984. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  82985. this.bones[0].computeAbsoluteTransforms();
  82986. this._lastAbsoluteTransformsUpdateId = renderId;
  82987. }
  82988. };
  82989. /**
  82990. * Gets the root pose matrix
  82991. * @returns a matrix
  82992. */
  82993. Skeleton.prototype.getPoseMatrix = function () {
  82994. var poseMatrix = null;
  82995. if (this._meshesWithPoseMatrix.length > 0) {
  82996. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  82997. }
  82998. return poseMatrix;
  82999. };
  83000. /**
  83001. * Sorts bones per internal index
  83002. */
  83003. Skeleton.prototype.sortBones = function () {
  83004. var bones = new Array();
  83005. var visited = new Array(this.bones.length);
  83006. for (var index = 0; index < this.bones.length; index++) {
  83007. this._sortBones(index, bones, visited);
  83008. }
  83009. this.bones = bones;
  83010. };
  83011. Skeleton.prototype._sortBones = function (index, bones, visited) {
  83012. if (visited[index]) {
  83013. return;
  83014. }
  83015. visited[index] = true;
  83016. var bone = this.bones[index];
  83017. if (bone._index === undefined) {
  83018. bone._index = index;
  83019. }
  83020. var parentBone = bone.getParent();
  83021. if (parentBone) {
  83022. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  83023. }
  83024. bones.push(bone);
  83025. };
  83026. return Skeleton;
  83027. }());
  83028. BABYLON.Skeleton = Skeleton;
  83029. })(BABYLON || (BABYLON = {}));
  83030. //# sourceMappingURL=babylon.skeleton.js.map
  83031. var BABYLON;
  83032. (function (BABYLON) {
  83033. ;
  83034. /**
  83035. * This groups tools to convert HDR texture to native colors array.
  83036. */
  83037. var HDRTools = /** @class */ (function () {
  83038. function HDRTools() {
  83039. }
  83040. HDRTools.Ldexp = function (mantissa, exponent) {
  83041. if (exponent > 1023) {
  83042. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  83043. }
  83044. if (exponent < -1074) {
  83045. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  83046. }
  83047. return mantissa * Math.pow(2, exponent);
  83048. };
  83049. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  83050. if (exponent > 0) { /*nonzero pixel*/
  83051. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  83052. float32array[index + 0] = red * exponent;
  83053. float32array[index + 1] = green * exponent;
  83054. float32array[index + 2] = blue * exponent;
  83055. }
  83056. else {
  83057. float32array[index + 0] = 0;
  83058. float32array[index + 1] = 0;
  83059. float32array[index + 2] = 0;
  83060. }
  83061. };
  83062. HDRTools.readStringLine = function (uint8array, startIndex) {
  83063. var line = "";
  83064. var character = "";
  83065. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  83066. character = String.fromCharCode(uint8array[i]);
  83067. if (character == "\n") {
  83068. break;
  83069. }
  83070. line += character;
  83071. }
  83072. return line;
  83073. };
  83074. /**
  83075. * Reads header information from an RGBE texture stored in a native array.
  83076. * More information on this format are available here:
  83077. * https://en.wikipedia.org/wiki/RGBE_image_format
  83078. *
  83079. * @param uint8array The binary file stored in native array.
  83080. * @return The header information.
  83081. */
  83082. HDRTools.RGBE_ReadHeader = function (uint8array) {
  83083. var height = 0;
  83084. var width = 0;
  83085. var line = this.readStringLine(uint8array, 0);
  83086. if (line[0] != '#' || line[1] != '?') {
  83087. throw "Bad HDR Format.";
  83088. }
  83089. var endOfHeader = false;
  83090. var findFormat = false;
  83091. var lineIndex = 0;
  83092. do {
  83093. lineIndex += (line.length + 1);
  83094. line = this.readStringLine(uint8array, lineIndex);
  83095. if (line == "FORMAT=32-bit_rle_rgbe") {
  83096. findFormat = true;
  83097. }
  83098. else if (line.length == 0) {
  83099. endOfHeader = true;
  83100. }
  83101. } while (!endOfHeader);
  83102. if (!findFormat) {
  83103. throw "HDR Bad header format, unsupported FORMAT";
  83104. }
  83105. lineIndex += (line.length + 1);
  83106. line = this.readStringLine(uint8array, lineIndex);
  83107. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  83108. var match = sizeRegexp.exec(line);
  83109. // TODO. Support +Y and -X if needed.
  83110. if (!match || match.length < 3) {
  83111. throw "HDR Bad header format, no size";
  83112. }
  83113. width = parseInt(match[2]);
  83114. height = parseInt(match[1]);
  83115. if (width < 8 || width > 0x7fff) {
  83116. throw "HDR Bad header format, unsupported size";
  83117. }
  83118. lineIndex += (line.length + 1);
  83119. return {
  83120. height: height,
  83121. width: width,
  83122. dataPosition: lineIndex
  83123. };
  83124. };
  83125. /**
  83126. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  83127. * This RGBE texture needs to store the information as a panorama.
  83128. *
  83129. * More information on this format are available here:
  83130. * https://en.wikipedia.org/wiki/RGBE_image_format
  83131. *
  83132. * @param buffer The binary file stored in an array buffer.
  83133. * @param size The expected size of the extracted cubemap.
  83134. * @return The Cube Map information.
  83135. */
  83136. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  83137. var uint8array = new Uint8Array(buffer);
  83138. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  83139. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83140. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  83141. return cubeMapData;
  83142. };
  83143. /**
  83144. * Returns the pixels data extracted from an RGBE texture.
  83145. * This pixels will be stored left to right up to down in the R G B order in one array.
  83146. *
  83147. * More information on this format are available here:
  83148. * https://en.wikipedia.org/wiki/RGBE_image_format
  83149. *
  83150. * @param uint8array The binary file stored in an array buffer.
  83151. * @param hdrInfo The header information of the file.
  83152. * @return The pixels data in RGB right to left up to down order.
  83153. */
  83154. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  83155. // Keep for multi format supports.
  83156. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  83157. };
  83158. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  83159. var num_scanlines = hdrInfo.height;
  83160. var scanline_width = hdrInfo.width;
  83161. var a, b, c, d, count;
  83162. var dataIndex = hdrInfo.dataPosition;
  83163. var index = 0, endIndex = 0, i = 0;
  83164. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  83165. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  83166. // 3 channels of 4 bytes per pixel in float.
  83167. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  83168. var resultArray = new Float32Array(resultBuffer);
  83169. // read in each successive scanline
  83170. while (num_scanlines > 0) {
  83171. a = uint8array[dataIndex++];
  83172. b = uint8array[dataIndex++];
  83173. c = uint8array[dataIndex++];
  83174. d = uint8array[dataIndex++];
  83175. if (a != 2 || b != 2 || (c & 0x80)) {
  83176. // this file is not run length encoded
  83177. throw "HDR Bad header format, not RLE";
  83178. }
  83179. if (((c << 8) | d) != scanline_width) {
  83180. throw "HDR Bad header format, wrong scan line width";
  83181. }
  83182. index = 0;
  83183. // read each of the four channels for the scanline into the buffer
  83184. for (i = 0; i < 4; i++) {
  83185. endIndex = (i + 1) * scanline_width;
  83186. while (index < endIndex) {
  83187. a = uint8array[dataIndex++];
  83188. b = uint8array[dataIndex++];
  83189. if (a > 128) {
  83190. // a run of the same value
  83191. count = a - 128;
  83192. if ((count == 0) || (count > endIndex - index)) {
  83193. throw "HDR Bad Format, bad scanline data (run)";
  83194. }
  83195. while (count-- > 0) {
  83196. scanLineArray[index++] = b;
  83197. }
  83198. }
  83199. else {
  83200. // a non-run
  83201. count = a;
  83202. if ((count == 0) || (count > endIndex - index)) {
  83203. throw "HDR Bad Format, bad scanline data (non-run)";
  83204. }
  83205. scanLineArray[index++] = b;
  83206. if (--count > 0) {
  83207. for (var j = 0; j < count; j++) {
  83208. scanLineArray[index++] = uint8array[dataIndex++];
  83209. }
  83210. }
  83211. }
  83212. }
  83213. }
  83214. // now convert data from buffer into floats
  83215. for (i = 0; i < scanline_width; i++) {
  83216. a = scanLineArray[i];
  83217. b = scanLineArray[i + scanline_width];
  83218. c = scanLineArray[i + 2 * scanline_width];
  83219. d = scanLineArray[i + 3 * scanline_width];
  83220. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  83221. }
  83222. num_scanlines--;
  83223. }
  83224. return resultArray;
  83225. };
  83226. return HDRTools;
  83227. }());
  83228. BABYLON.HDRTools = HDRTools;
  83229. })(BABYLON || (BABYLON = {}));
  83230. //# sourceMappingURL=babylon.hdr.js.map
  83231. var BABYLON;
  83232. (function (BABYLON) {
  83233. /**
  83234. * This represents a texture coming from an HDR input.
  83235. *
  83236. * The only supported format is currently panorama picture stored in RGBE format.
  83237. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83238. */
  83239. var HDRCubeTexture = /** @class */ (function (_super) {
  83240. __extends(HDRCubeTexture, _super);
  83241. /**
  83242. * Instantiates an HDRTexture from the following parameters.
  83243. *
  83244. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83245. * @param scene The scene the texture will be used in
  83246. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83247. * @param noMipmap Forces to not generate the mipmap if true
  83248. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83249. * @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)
  83250. * @param reserved Reserved flag for internal use.
  83251. */
  83252. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83253. if (noMipmap === void 0) { noMipmap = false; }
  83254. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83255. if (gammaSpace === void 0) { gammaSpace = false; }
  83256. if (reserved === void 0) { reserved = false; }
  83257. if (onLoad === void 0) { onLoad = null; }
  83258. if (onError === void 0) { onError = null; }
  83259. var _this = _super.call(this, scene) || this;
  83260. _this._generateHarmonics = true;
  83261. _this._onLoad = null;
  83262. _this._onError = null;
  83263. /**
  83264. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83265. */
  83266. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83267. _this._isBlocking = true;
  83268. _this._rotationY = 0;
  83269. /**
  83270. * Gets or sets the center of the bounding box associated with the cube texture
  83271. * It must define where the camera used to render the texture was set
  83272. */
  83273. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83274. if (!url) {
  83275. return _this;
  83276. }
  83277. _this.name = url;
  83278. _this.url = url;
  83279. _this.hasAlpha = false;
  83280. _this.isCube = true;
  83281. _this._textureMatrix = BABYLON.Matrix.Identity();
  83282. _this._onLoad = onLoad;
  83283. _this._onError = onError;
  83284. _this.gammaSpace = gammaSpace;
  83285. _this._noMipmap = noMipmap;
  83286. _this._size = size;
  83287. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83288. if (!_this._texture) {
  83289. if (!scene.useDelayedTextureLoading) {
  83290. _this.loadTexture();
  83291. }
  83292. else {
  83293. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83294. }
  83295. }
  83296. return _this;
  83297. }
  83298. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83299. /**
  83300. * Gets wether or not the texture is blocking during loading.
  83301. */
  83302. get: function () {
  83303. return this._isBlocking;
  83304. },
  83305. /**
  83306. * Sets wether or not the texture is blocking during loading.
  83307. */
  83308. set: function (value) {
  83309. this._isBlocking = value;
  83310. },
  83311. enumerable: true,
  83312. configurable: true
  83313. });
  83314. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83315. /**
  83316. * Gets texture matrix rotation angle around Y axis radians.
  83317. */
  83318. get: function () {
  83319. return this._rotationY;
  83320. },
  83321. /**
  83322. * Sets texture matrix rotation angle around Y axis in radians.
  83323. */
  83324. set: function (value) {
  83325. this._rotationY = value;
  83326. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83327. },
  83328. enumerable: true,
  83329. configurable: true
  83330. });
  83331. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83332. get: function () {
  83333. return this._boundingBoxSize;
  83334. },
  83335. /**
  83336. * Gets or sets the size of the bounding box associated with the cube texture
  83337. * When defined, the cubemap will switch to local mode
  83338. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83339. * @example https://www.babylonjs-playground.com/#RNASML
  83340. */
  83341. set: function (value) {
  83342. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83343. return;
  83344. }
  83345. this._boundingBoxSize = value;
  83346. var scene = this.getScene();
  83347. if (scene) {
  83348. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83349. }
  83350. },
  83351. enumerable: true,
  83352. configurable: true
  83353. });
  83354. /**
  83355. * Occurs when the file is raw .hdr file.
  83356. */
  83357. HDRCubeTexture.prototype.loadTexture = function () {
  83358. var _this = this;
  83359. var callback = function (buffer) {
  83360. _this.lodGenerationOffset = 0.0;
  83361. _this.lodGenerationScale = 0.8;
  83362. var scene = _this.getScene();
  83363. if (!scene) {
  83364. return null;
  83365. }
  83366. // Extract the raw linear data.
  83367. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83368. // Generate harmonics if needed.
  83369. if (_this._generateHarmonics) {
  83370. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83371. _this.sphericalPolynomial = sphericalPolynomial;
  83372. }
  83373. var results = [];
  83374. var byteArray = null;
  83375. // Push each faces.
  83376. for (var j = 0; j < 6; j++) {
  83377. // Create uintarray fallback.
  83378. if (!scene.getEngine().getCaps().textureFloat) {
  83379. // 3 channels of 1 bytes per pixel in bytes.
  83380. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83381. byteArray = new Uint8Array(byteBuffer);
  83382. }
  83383. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83384. // If special cases.
  83385. if (_this.gammaSpace || byteArray) {
  83386. for (var i = 0; i < _this._size * _this._size; i++) {
  83387. // Put in gamma space if requested.
  83388. if (_this.gammaSpace) {
  83389. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83390. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83391. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83392. }
  83393. // Convert to int texture for fallback.
  83394. if (byteArray) {
  83395. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83396. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83397. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83398. // May use luminance instead if the result is not accurate.
  83399. var max = Math.max(Math.max(r, g), b);
  83400. if (max > 255) {
  83401. var scale = 255 / max;
  83402. r *= scale;
  83403. g *= scale;
  83404. b *= scale;
  83405. }
  83406. byteArray[(i * 3) + 0] = r;
  83407. byteArray[(i * 3) + 1] = g;
  83408. byteArray[(i * 3) + 2] = b;
  83409. }
  83410. }
  83411. }
  83412. if (byteArray) {
  83413. results.push(byteArray);
  83414. }
  83415. else {
  83416. results.push(dataFace);
  83417. }
  83418. }
  83419. return results;
  83420. };
  83421. var scene = this.getScene();
  83422. if (scene) {
  83423. 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);
  83424. }
  83425. };
  83426. HDRCubeTexture.prototype.clone = function () {
  83427. var scene = this.getScene();
  83428. if (!scene) {
  83429. return this;
  83430. }
  83431. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83432. // Base texture
  83433. newTexture.level = this.level;
  83434. newTexture.wrapU = this.wrapU;
  83435. newTexture.wrapV = this.wrapV;
  83436. newTexture.coordinatesIndex = this.coordinatesIndex;
  83437. newTexture.coordinatesMode = this.coordinatesMode;
  83438. return newTexture;
  83439. };
  83440. // Methods
  83441. HDRCubeTexture.prototype.delayLoad = function () {
  83442. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83443. return;
  83444. }
  83445. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83446. this._texture = this._getFromCache(this.url, this._noMipmap);
  83447. if (!this._texture) {
  83448. this.loadTexture();
  83449. }
  83450. };
  83451. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83452. return this._textureMatrix;
  83453. };
  83454. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83455. this._textureMatrix = value;
  83456. };
  83457. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83458. var texture = null;
  83459. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83460. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83461. texture.name = parsedTexture.name;
  83462. texture.hasAlpha = parsedTexture.hasAlpha;
  83463. texture.level = parsedTexture.level;
  83464. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83465. texture.isBlocking = parsedTexture.isBlocking;
  83466. }
  83467. if (texture) {
  83468. if (parsedTexture.boundingBoxPosition) {
  83469. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83470. }
  83471. if (parsedTexture.boundingBoxSize) {
  83472. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83473. }
  83474. if (parsedTexture.rotationY) {
  83475. texture.rotationY = parsedTexture.rotationY;
  83476. }
  83477. }
  83478. return texture;
  83479. };
  83480. HDRCubeTexture.prototype.serialize = function () {
  83481. if (!this.name) {
  83482. return null;
  83483. }
  83484. var serializationObject = {};
  83485. serializationObject.name = this.name;
  83486. serializationObject.hasAlpha = this.hasAlpha;
  83487. serializationObject.isCube = true;
  83488. serializationObject.level = this.level;
  83489. serializationObject.size = this._size;
  83490. serializationObject.coordinatesMode = this.coordinatesMode;
  83491. serializationObject.useInGammaSpace = this.gammaSpace;
  83492. serializationObject.generateHarmonics = this._generateHarmonics;
  83493. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83494. serializationObject.noMipmap = this._noMipmap;
  83495. serializationObject.isBlocking = this._isBlocking;
  83496. serializationObject.rotationY = this._rotationY;
  83497. return serializationObject;
  83498. };
  83499. HDRCubeTexture._facesMapping = [
  83500. "right",
  83501. "left",
  83502. "up",
  83503. "down",
  83504. "front",
  83505. "back"
  83506. ];
  83507. return HDRCubeTexture;
  83508. }(BABYLON.BaseTexture));
  83509. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83510. })(BABYLON || (BABYLON = {}));
  83511. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83512. var BABYLON;
  83513. (function (BABYLON) {
  83514. /**
  83515. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  83516. */
  83517. var PanoramaToCubeMapTools = /** @class */ (function () {
  83518. function PanoramaToCubeMapTools() {
  83519. }
  83520. /**
  83521. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  83522. *
  83523. * @param float32Array The source data.
  83524. * @param inputWidth The width of the input panorama.
  83525. * @param inputhHeight The height of the input panorama.
  83526. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  83527. * @return The cubemap data
  83528. */
  83529. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  83530. if (!float32Array) {
  83531. throw "ConvertPanoramaToCubemap: input cannot be null";
  83532. }
  83533. if (float32Array.length != inputWidth * inputHeight * 3) {
  83534. throw "ConvertPanoramaToCubemap: input size is wrong";
  83535. }
  83536. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  83537. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  83538. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  83539. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  83540. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  83541. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  83542. return {
  83543. front: textureFront,
  83544. back: textureBack,
  83545. left: textureLeft,
  83546. right: textureRight,
  83547. up: textureUp,
  83548. down: textureDown,
  83549. size: size,
  83550. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  83551. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  83552. gammaSpace: false,
  83553. };
  83554. };
  83555. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  83556. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  83557. var textureArray = new Float32Array(buffer);
  83558. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  83559. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  83560. var dy = 1 / texSize;
  83561. var fy = 0;
  83562. for (var y = 0; y < texSize; y++) {
  83563. var xv1 = faceData[0];
  83564. var xv2 = faceData[2];
  83565. for (var x = 0; x < texSize; x++) {
  83566. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  83567. v.normalize();
  83568. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  83569. // 3 channels per pixels
  83570. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  83571. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  83572. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  83573. xv1 = xv1.add(rotDX1);
  83574. xv2 = xv2.add(rotDX2);
  83575. }
  83576. fy += dy;
  83577. }
  83578. return textureArray;
  83579. };
  83580. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  83581. var theta = Math.atan2(vDir.z, vDir.x);
  83582. var phi = Math.acos(vDir.y);
  83583. while (theta < -Math.PI)
  83584. theta += 2 * Math.PI;
  83585. while (theta > Math.PI)
  83586. theta -= 2 * Math.PI;
  83587. var dx = theta / Math.PI;
  83588. var dy = phi / Math.PI;
  83589. // recenter.
  83590. dx = dx * 0.5 + 0.5;
  83591. var px = Math.round(dx * inputWidth);
  83592. if (px < 0)
  83593. px = 0;
  83594. else if (px >= inputWidth)
  83595. px = inputWidth - 1;
  83596. var py = Math.round(dy * inputHeight);
  83597. if (py < 0)
  83598. py = 0;
  83599. else if (py >= inputHeight)
  83600. py = inputHeight - 1;
  83601. var inputY = (inputHeight - py - 1);
  83602. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  83603. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  83604. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  83605. return {
  83606. r: r,
  83607. g: g,
  83608. b: b
  83609. };
  83610. };
  83611. PanoramaToCubeMapTools.FACE_FRONT = [
  83612. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83613. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83614. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83615. new BABYLON.Vector3(1.0, 1.0, -1.0)
  83616. ];
  83617. PanoramaToCubeMapTools.FACE_BACK = [
  83618. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83619. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83620. new BABYLON.Vector3(1.0, 1.0, 1.0),
  83621. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  83622. ];
  83623. PanoramaToCubeMapTools.FACE_RIGHT = [
  83624. new BABYLON.Vector3(1.0, -1.0, -1.0),
  83625. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83626. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83627. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83628. ];
  83629. PanoramaToCubeMapTools.FACE_LEFT = [
  83630. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83631. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83632. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83633. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  83634. ];
  83635. PanoramaToCubeMapTools.FACE_DOWN = [
  83636. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  83637. new BABYLON.Vector3(1.0, 1.0, -1.0),
  83638. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  83639. new BABYLON.Vector3(1.0, 1.0, 1.0)
  83640. ];
  83641. PanoramaToCubeMapTools.FACE_UP = [
  83642. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  83643. new BABYLON.Vector3(1.0, -1.0, 1.0),
  83644. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  83645. new BABYLON.Vector3(1.0, -1.0, -1.0)
  83646. ];
  83647. return PanoramaToCubeMapTools;
  83648. }());
  83649. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  83650. })(BABYLON || (BABYLON = {}));
  83651. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  83652. var BABYLON;
  83653. (function (BABYLON) {
  83654. var IndexedVector2 = /** @class */ (function (_super) {
  83655. __extends(IndexedVector2, _super);
  83656. function IndexedVector2(original, index) {
  83657. var _this = _super.call(this, original.x, original.y) || this;
  83658. _this.index = index;
  83659. return _this;
  83660. }
  83661. return IndexedVector2;
  83662. }(BABYLON.Vector2));
  83663. var PolygonPoints = /** @class */ (function () {
  83664. function PolygonPoints() {
  83665. this.elements = new Array();
  83666. }
  83667. PolygonPoints.prototype.add = function (originalPoints) {
  83668. var _this = this;
  83669. var result = new Array();
  83670. originalPoints.forEach(function (point) {
  83671. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83672. var newPoint = new IndexedVector2(point, _this.elements.length);
  83673. result.push(newPoint);
  83674. _this.elements.push(newPoint);
  83675. }
  83676. });
  83677. return result;
  83678. };
  83679. PolygonPoints.prototype.computeBounds = function () {
  83680. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83681. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83682. this.elements.forEach(function (point) {
  83683. // x
  83684. if (point.x < lmin.x) {
  83685. lmin.x = point.x;
  83686. }
  83687. else if (point.x > lmax.x) {
  83688. lmax.x = point.x;
  83689. }
  83690. // y
  83691. if (point.y < lmin.y) {
  83692. lmin.y = point.y;
  83693. }
  83694. else if (point.y > lmax.y) {
  83695. lmax.y = point.y;
  83696. }
  83697. });
  83698. return {
  83699. min: lmin,
  83700. max: lmax,
  83701. width: lmax.x - lmin.x,
  83702. height: lmax.y - lmin.y
  83703. };
  83704. };
  83705. return PolygonPoints;
  83706. }());
  83707. var Polygon = /** @class */ (function () {
  83708. function Polygon() {
  83709. }
  83710. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83711. return [
  83712. new BABYLON.Vector2(xmin, ymin),
  83713. new BABYLON.Vector2(xmax, ymin),
  83714. new BABYLON.Vector2(xmax, ymax),
  83715. new BABYLON.Vector2(xmin, ymax)
  83716. ];
  83717. };
  83718. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83719. if (cx === void 0) { cx = 0; }
  83720. if (cy === void 0) { cy = 0; }
  83721. if (numberOfSides === void 0) { numberOfSides = 32; }
  83722. var result = new Array();
  83723. var angle = 0;
  83724. var increment = (Math.PI * 2) / numberOfSides;
  83725. for (var i = 0; i < numberOfSides; i++) {
  83726. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83727. angle -= increment;
  83728. }
  83729. return result;
  83730. };
  83731. Polygon.Parse = function (input) {
  83732. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83733. var i, result = [];
  83734. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83735. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83736. }
  83737. return result;
  83738. };
  83739. Polygon.StartingAt = function (x, y) {
  83740. return BABYLON.Path2.StartingAt(x, y);
  83741. };
  83742. return Polygon;
  83743. }());
  83744. BABYLON.Polygon = Polygon;
  83745. var PolygonMeshBuilder = /** @class */ (function () {
  83746. function PolygonMeshBuilder(name, contours, scene) {
  83747. this._points = new PolygonPoints();
  83748. this._outlinepoints = new PolygonPoints();
  83749. this._holes = new Array();
  83750. this._epoints = new Array();
  83751. this._eholes = new Array();
  83752. this._name = name;
  83753. this._scene = scene;
  83754. var points;
  83755. if (contours instanceof BABYLON.Path2) {
  83756. points = contours.getPoints();
  83757. }
  83758. else {
  83759. points = contours;
  83760. }
  83761. this._addToepoint(points);
  83762. this._points.add(points);
  83763. this._outlinepoints.add(points);
  83764. if (typeof earcut === 'undefined') {
  83765. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83766. }
  83767. }
  83768. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83769. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83770. var p = points_1[_i];
  83771. this._epoints.push(p.x, p.y);
  83772. }
  83773. };
  83774. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83775. this._points.add(hole);
  83776. var holepoints = new PolygonPoints();
  83777. holepoints.add(hole);
  83778. this._holes.push(holepoints);
  83779. this._eholes.push(this._epoints.length / 2);
  83780. this._addToepoint(hole);
  83781. return this;
  83782. };
  83783. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83784. var _this = this;
  83785. if (updatable === void 0) { updatable = false; }
  83786. if (depth === void 0) { depth = 0; }
  83787. var result = new BABYLON.Mesh(this._name, this._scene);
  83788. var normals = new Array();
  83789. var positions = new Array();
  83790. var uvs = new Array();
  83791. var bounds = this._points.computeBounds();
  83792. this._points.elements.forEach(function (p) {
  83793. normals.push(0, 1.0, 0);
  83794. positions.push(p.x, 0, p.y);
  83795. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83796. });
  83797. var indices = new Array();
  83798. var res = earcut(this._epoints, this._eholes, 2);
  83799. for (var i = 0; i < res.length; i++) {
  83800. indices.push(res[i]);
  83801. }
  83802. if (depth > 0) {
  83803. var positionscount = (positions.length / 3); //get the current pointcount
  83804. this._points.elements.forEach(function (p) {
  83805. normals.push(0, -1.0, 0);
  83806. positions.push(p.x, -depth, p.y);
  83807. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83808. });
  83809. var totalCount = indices.length;
  83810. for (var i = 0; i < totalCount; i += 3) {
  83811. var i0 = indices[i + 0];
  83812. var i1 = indices[i + 1];
  83813. var i2 = indices[i + 2];
  83814. indices.push(i2 + positionscount);
  83815. indices.push(i1 + positionscount);
  83816. indices.push(i0 + positionscount);
  83817. }
  83818. //Add the sides
  83819. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83820. this._holes.forEach(function (hole) {
  83821. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83822. });
  83823. }
  83824. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83825. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83826. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83827. result.setIndices(indices);
  83828. return result;
  83829. };
  83830. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83831. var StartIndex = positions.length / 3;
  83832. var ulength = 0;
  83833. for (var i = 0; i < points.elements.length; i++) {
  83834. var p = points.elements[i];
  83835. var p1;
  83836. if ((i + 1) > points.elements.length - 1) {
  83837. p1 = points.elements[0];
  83838. }
  83839. else {
  83840. p1 = points.elements[i + 1];
  83841. }
  83842. positions.push(p.x, 0, p.y);
  83843. positions.push(p.x, -depth, p.y);
  83844. positions.push(p1.x, 0, p1.y);
  83845. positions.push(p1.x, -depth, p1.y);
  83846. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83847. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83848. var v3 = v2.subtract(v1);
  83849. var v4 = new BABYLON.Vector3(0, 1, 0);
  83850. var vn = BABYLON.Vector3.Cross(v3, v4);
  83851. vn = vn.normalize();
  83852. uvs.push(ulength / bounds.width, 0);
  83853. uvs.push(ulength / bounds.width, 1);
  83854. ulength += v3.length();
  83855. uvs.push((ulength / bounds.width), 0);
  83856. uvs.push((ulength / bounds.width), 1);
  83857. if (!flip) {
  83858. normals.push(-vn.x, -vn.y, -vn.z);
  83859. normals.push(-vn.x, -vn.y, -vn.z);
  83860. normals.push(-vn.x, -vn.y, -vn.z);
  83861. normals.push(-vn.x, -vn.y, -vn.z);
  83862. indices.push(StartIndex);
  83863. indices.push(StartIndex + 1);
  83864. indices.push(StartIndex + 2);
  83865. indices.push(StartIndex + 1);
  83866. indices.push(StartIndex + 3);
  83867. indices.push(StartIndex + 2);
  83868. }
  83869. else {
  83870. normals.push(vn.x, vn.y, vn.z);
  83871. normals.push(vn.x, vn.y, vn.z);
  83872. normals.push(vn.x, vn.y, vn.z);
  83873. normals.push(vn.x, vn.y, vn.z);
  83874. indices.push(StartIndex);
  83875. indices.push(StartIndex + 2);
  83876. indices.push(StartIndex + 1);
  83877. indices.push(StartIndex + 1);
  83878. indices.push(StartIndex + 2);
  83879. indices.push(StartIndex + 3);
  83880. }
  83881. StartIndex += 4;
  83882. }
  83883. ;
  83884. };
  83885. return PolygonMeshBuilder;
  83886. }());
  83887. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83888. })(BABYLON || (BABYLON = {}));
  83889. //# sourceMappingURL=babylon.polygonMesh.js.map
  83890. var BABYLON;
  83891. (function (BABYLON) {
  83892. // Unique ID when we import meshes from Babylon to CSG
  83893. var currentCSGMeshId = 0;
  83894. // # class Vertex
  83895. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83896. // one to provide additional features like texture coordinates and vertex
  83897. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83898. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83899. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83900. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83901. // is not used anywhere else.
  83902. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83903. var Vertex = /** @class */ (function () {
  83904. function Vertex(pos, normal, uv) {
  83905. this.pos = pos;
  83906. this.normal = normal;
  83907. this.uv = uv;
  83908. }
  83909. Vertex.prototype.clone = function () {
  83910. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83911. };
  83912. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83913. // orientation of a polygon is flipped.
  83914. Vertex.prototype.flip = function () {
  83915. this.normal = this.normal.scale(-1);
  83916. };
  83917. // Create a new vertex between this vertex and `other` by linearly
  83918. // interpolating all properties using a parameter of `t`. Subclasses should
  83919. // override this to interpolate additional properties.
  83920. Vertex.prototype.interpolate = function (other, t) {
  83921. 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));
  83922. };
  83923. return Vertex;
  83924. }());
  83925. // # class Plane
  83926. // Represents a plane in 3D space.
  83927. var Plane = /** @class */ (function () {
  83928. function Plane(normal, w) {
  83929. this.normal = normal;
  83930. this.w = w;
  83931. }
  83932. Plane.FromPoints = function (a, b, c) {
  83933. var v0 = c.subtract(a);
  83934. var v1 = b.subtract(a);
  83935. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83936. return null;
  83937. }
  83938. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83939. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83940. };
  83941. Plane.prototype.clone = function () {
  83942. return new Plane(this.normal.clone(), this.w);
  83943. };
  83944. Plane.prototype.flip = function () {
  83945. this.normal.scaleInPlace(-1);
  83946. this.w = -this.w;
  83947. };
  83948. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83949. // fragments in the appropriate lists. Coplanar polygons go into either
  83950. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83951. // respect to this plane. Polygons in front or in back of this plane go into
  83952. // either `front` or `back`.
  83953. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83954. var COPLANAR = 0;
  83955. var FRONT = 1;
  83956. var BACK = 2;
  83957. var SPANNING = 3;
  83958. // Classify each point as well as the entire polygon into one of the above
  83959. // four classes.
  83960. var polygonType = 0;
  83961. var types = [];
  83962. var i;
  83963. var t;
  83964. for (i = 0; i < polygon.vertices.length; i++) {
  83965. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83966. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83967. polygonType |= type;
  83968. types.push(type);
  83969. }
  83970. // Put the polygon in the correct list, splitting it when necessary.
  83971. switch (polygonType) {
  83972. case COPLANAR:
  83973. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83974. break;
  83975. case FRONT:
  83976. front.push(polygon);
  83977. break;
  83978. case BACK:
  83979. back.push(polygon);
  83980. break;
  83981. case SPANNING:
  83982. var f = [], b = [];
  83983. for (i = 0; i < polygon.vertices.length; i++) {
  83984. var j = (i + 1) % polygon.vertices.length;
  83985. var ti = types[i], tj = types[j];
  83986. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83987. if (ti !== BACK)
  83988. f.push(vi);
  83989. if (ti !== FRONT)
  83990. b.push(ti !== BACK ? vi.clone() : vi);
  83991. if ((ti | tj) === SPANNING) {
  83992. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83993. var v = vi.interpolate(vj, t);
  83994. f.push(v);
  83995. b.push(v.clone());
  83996. }
  83997. }
  83998. var poly;
  83999. if (f.length >= 3) {
  84000. poly = new Polygon(f, polygon.shared);
  84001. if (poly.plane)
  84002. front.push(poly);
  84003. }
  84004. if (b.length >= 3) {
  84005. poly = new Polygon(b, polygon.shared);
  84006. if (poly.plane)
  84007. back.push(poly);
  84008. }
  84009. break;
  84010. }
  84011. };
  84012. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  84013. // point is on the plane.
  84014. Plane.EPSILON = 1e-5;
  84015. return Plane;
  84016. }());
  84017. // # class Polygon
  84018. // Represents a convex polygon. The vertices used to initialize a polygon must
  84019. // be coplanar and form a convex loop.
  84020. //
  84021. // Each convex polygon has a `shared` property, which is shared between all
  84022. // polygons that are clones of each other or were split from the same polygon.
  84023. // This can be used to define per-polygon properties (such as surface color).
  84024. var Polygon = /** @class */ (function () {
  84025. function Polygon(vertices, shared) {
  84026. this.vertices = vertices;
  84027. this.shared = shared;
  84028. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  84029. }
  84030. Polygon.prototype.clone = function () {
  84031. var vertices = this.vertices.map(function (v) { return v.clone(); });
  84032. return new Polygon(vertices, this.shared);
  84033. };
  84034. Polygon.prototype.flip = function () {
  84035. this.vertices.reverse().map(function (v) { v.flip(); });
  84036. this.plane.flip();
  84037. };
  84038. return Polygon;
  84039. }());
  84040. // # class Node
  84041. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  84042. // by picking a polygon to split along. That polygon (and all other coplanar
  84043. // polygons) are added directly to that node and the other polygons are added to
  84044. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  84045. // no distinction between internal and leaf nodes.
  84046. var Node = /** @class */ (function () {
  84047. function Node(polygons) {
  84048. this.plane = null;
  84049. this.front = null;
  84050. this.back = null;
  84051. this.polygons = new Array();
  84052. if (polygons) {
  84053. this.build(polygons);
  84054. }
  84055. }
  84056. Node.prototype.clone = function () {
  84057. var node = new Node();
  84058. node.plane = this.plane && this.plane.clone();
  84059. node.front = this.front && this.front.clone();
  84060. node.back = this.back && this.back.clone();
  84061. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  84062. return node;
  84063. };
  84064. // Convert solid space to empty space and empty space to solid space.
  84065. Node.prototype.invert = function () {
  84066. for (var i = 0; i < this.polygons.length; i++) {
  84067. this.polygons[i].flip();
  84068. }
  84069. if (this.plane) {
  84070. this.plane.flip();
  84071. }
  84072. if (this.front) {
  84073. this.front.invert();
  84074. }
  84075. if (this.back) {
  84076. this.back.invert();
  84077. }
  84078. var temp = this.front;
  84079. this.front = this.back;
  84080. this.back = temp;
  84081. };
  84082. // Recursively remove all polygons in `polygons` that are inside this BSP
  84083. // tree.
  84084. Node.prototype.clipPolygons = function (polygons) {
  84085. if (!this.plane)
  84086. return polygons.slice();
  84087. var front = new Array(), back = new Array();
  84088. for (var i = 0; i < polygons.length; i++) {
  84089. this.plane.splitPolygon(polygons[i], front, back, front, back);
  84090. }
  84091. if (this.front) {
  84092. front = this.front.clipPolygons(front);
  84093. }
  84094. if (this.back) {
  84095. back = this.back.clipPolygons(back);
  84096. }
  84097. else {
  84098. back = [];
  84099. }
  84100. return front.concat(back);
  84101. };
  84102. // Remove all polygons in this BSP tree that are inside the other BSP tree
  84103. // `bsp`.
  84104. Node.prototype.clipTo = function (bsp) {
  84105. this.polygons = bsp.clipPolygons(this.polygons);
  84106. if (this.front)
  84107. this.front.clipTo(bsp);
  84108. if (this.back)
  84109. this.back.clipTo(bsp);
  84110. };
  84111. // Return a list of all polygons in this BSP tree.
  84112. Node.prototype.allPolygons = function () {
  84113. var polygons = this.polygons.slice();
  84114. if (this.front)
  84115. polygons = polygons.concat(this.front.allPolygons());
  84116. if (this.back)
  84117. polygons = polygons.concat(this.back.allPolygons());
  84118. return polygons;
  84119. };
  84120. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  84121. // new polygons are filtered down to the bottom of the tree and become new
  84122. // nodes there. Each set of polygons is partitioned using the first polygon
  84123. // (no heuristic is used to pick a good split).
  84124. Node.prototype.build = function (polygons) {
  84125. if (!polygons.length)
  84126. return;
  84127. if (!this.plane)
  84128. this.plane = polygons[0].plane.clone();
  84129. var front = new Array(), back = new Array();
  84130. for (var i = 0; i < polygons.length; i++) {
  84131. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  84132. }
  84133. if (front.length) {
  84134. if (!this.front)
  84135. this.front = new Node();
  84136. this.front.build(front);
  84137. }
  84138. if (back.length) {
  84139. if (!this.back)
  84140. this.back = new Node();
  84141. this.back.build(back);
  84142. }
  84143. };
  84144. return Node;
  84145. }());
  84146. var CSG = /** @class */ (function () {
  84147. function CSG() {
  84148. this.polygons = new Array();
  84149. }
  84150. // Convert BABYLON.Mesh to BABYLON.CSG
  84151. CSG.FromMesh = function (mesh) {
  84152. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  84153. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  84154. if (mesh instanceof BABYLON.Mesh) {
  84155. mesh.computeWorldMatrix(true);
  84156. matrix = mesh.getWorldMatrix();
  84157. meshPosition = mesh.position.clone();
  84158. meshRotation = mesh.rotation.clone();
  84159. if (mesh.rotationQuaternion) {
  84160. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  84161. }
  84162. meshScaling = mesh.scaling.clone();
  84163. }
  84164. else {
  84165. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  84166. }
  84167. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84168. var subMeshes = mesh.subMeshes;
  84169. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  84170. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  84171. vertices = [];
  84172. for (var j = 0; j < 3; j++) {
  84173. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  84174. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  84175. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  84176. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  84177. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  84178. vertex = new Vertex(position, normal, uv);
  84179. vertices.push(vertex);
  84180. }
  84181. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  84182. // To handle the case of degenerated triangle
  84183. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  84184. if (polygon.plane)
  84185. polygons.push(polygon);
  84186. }
  84187. }
  84188. var csg = CSG.FromPolygons(polygons);
  84189. csg.matrix = matrix;
  84190. csg.position = meshPosition;
  84191. csg.rotation = meshRotation;
  84192. csg.scaling = meshScaling;
  84193. csg.rotationQuaternion = meshRotationQuaternion;
  84194. currentCSGMeshId++;
  84195. return csg;
  84196. };
  84197. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  84198. CSG.FromPolygons = function (polygons) {
  84199. var csg = new CSG();
  84200. csg.polygons = polygons;
  84201. return csg;
  84202. };
  84203. CSG.prototype.clone = function () {
  84204. var csg = new CSG();
  84205. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  84206. csg.copyTransformAttributes(this);
  84207. return csg;
  84208. };
  84209. CSG.prototype.union = function (csg) {
  84210. var a = new Node(this.clone().polygons);
  84211. var b = new Node(csg.clone().polygons);
  84212. a.clipTo(b);
  84213. b.clipTo(a);
  84214. b.invert();
  84215. b.clipTo(a);
  84216. b.invert();
  84217. a.build(b.allPolygons());
  84218. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84219. };
  84220. CSG.prototype.unionInPlace = function (csg) {
  84221. var a = new Node(this.polygons);
  84222. var b = new Node(csg.polygons);
  84223. a.clipTo(b);
  84224. b.clipTo(a);
  84225. b.invert();
  84226. b.clipTo(a);
  84227. b.invert();
  84228. a.build(b.allPolygons());
  84229. this.polygons = a.allPolygons();
  84230. };
  84231. CSG.prototype.subtract = function (csg) {
  84232. var a = new Node(this.clone().polygons);
  84233. var b = new Node(csg.clone().polygons);
  84234. a.invert();
  84235. a.clipTo(b);
  84236. b.clipTo(a);
  84237. b.invert();
  84238. b.clipTo(a);
  84239. b.invert();
  84240. a.build(b.allPolygons());
  84241. a.invert();
  84242. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84243. };
  84244. CSG.prototype.subtractInPlace = function (csg) {
  84245. var a = new Node(this.polygons);
  84246. var b = new Node(csg.polygons);
  84247. a.invert();
  84248. a.clipTo(b);
  84249. b.clipTo(a);
  84250. b.invert();
  84251. b.clipTo(a);
  84252. b.invert();
  84253. a.build(b.allPolygons());
  84254. a.invert();
  84255. this.polygons = a.allPolygons();
  84256. };
  84257. CSG.prototype.intersect = function (csg) {
  84258. var a = new Node(this.clone().polygons);
  84259. var b = new Node(csg.clone().polygons);
  84260. a.invert();
  84261. b.clipTo(a);
  84262. b.invert();
  84263. a.clipTo(b);
  84264. b.clipTo(a);
  84265. a.build(b.allPolygons());
  84266. a.invert();
  84267. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84268. };
  84269. CSG.prototype.intersectInPlace = function (csg) {
  84270. var a = new Node(this.polygons);
  84271. var b = new Node(csg.polygons);
  84272. a.invert();
  84273. b.clipTo(a);
  84274. b.invert();
  84275. a.clipTo(b);
  84276. b.clipTo(a);
  84277. a.build(b.allPolygons());
  84278. a.invert();
  84279. this.polygons = a.allPolygons();
  84280. };
  84281. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84282. // not modified.
  84283. CSG.prototype.inverse = function () {
  84284. var csg = this.clone();
  84285. csg.inverseInPlace();
  84286. return csg;
  84287. };
  84288. CSG.prototype.inverseInPlace = function () {
  84289. this.polygons.map(function (p) { p.flip(); });
  84290. };
  84291. // This is used to keep meshes transformations so they can be restored
  84292. // when we build back a Babylon Mesh
  84293. // NB : All CSG operations are performed in world coordinates
  84294. CSG.prototype.copyTransformAttributes = function (csg) {
  84295. this.matrix = csg.matrix;
  84296. this.position = csg.position;
  84297. this.rotation = csg.rotation;
  84298. this.scaling = csg.scaling;
  84299. this.rotationQuaternion = csg.rotationQuaternion;
  84300. return this;
  84301. };
  84302. // Build Raw mesh from CSG
  84303. // Coordinates here are in world space
  84304. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84305. var matrix = this.matrix.clone();
  84306. matrix.invert();
  84307. 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;
  84308. if (keepSubMeshes) {
  84309. // Sort Polygons, since subMeshes are indices range
  84310. polygons.sort(function (a, b) {
  84311. if (a.shared.meshId === b.shared.meshId) {
  84312. return a.shared.subMeshId - b.shared.subMeshId;
  84313. }
  84314. else {
  84315. return a.shared.meshId - b.shared.meshId;
  84316. }
  84317. });
  84318. }
  84319. for (var i = 0, il = polygons.length; i < il; i++) {
  84320. polygon = polygons[i];
  84321. // Building SubMeshes
  84322. if (!subMesh_dict[polygon.shared.meshId]) {
  84323. subMesh_dict[polygon.shared.meshId] = {};
  84324. }
  84325. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84326. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84327. indexStart: +Infinity,
  84328. indexEnd: -Infinity,
  84329. materialIndex: polygon.shared.materialIndex
  84330. };
  84331. }
  84332. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84333. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84334. polygonIndices[0] = 0;
  84335. polygonIndices[1] = j - 1;
  84336. polygonIndices[2] = j;
  84337. for (var k = 0; k < 3; k++) {
  84338. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84339. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84340. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84341. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84342. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84343. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84344. // Check if 2 points can be merged
  84345. if (!(typeof vertex_idx !== 'undefined' &&
  84346. normals[vertex_idx * 3] === localNormal.x &&
  84347. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84348. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84349. uvs[vertex_idx * 2] === uv.x &&
  84350. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84351. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84352. uvs.push(uv.x, uv.y);
  84353. normals.push(normal.x, normal.y, normal.z);
  84354. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84355. }
  84356. indices.push(vertex_idx);
  84357. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84358. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84359. currentIndex++;
  84360. }
  84361. }
  84362. }
  84363. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84364. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84365. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84366. mesh.setIndices(indices, null);
  84367. if (keepSubMeshes) {
  84368. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84369. var materialIndexOffset = 0, materialMaxIndex;
  84370. mesh.subMeshes = new Array();
  84371. for (var m in subMesh_dict) {
  84372. materialMaxIndex = -1;
  84373. for (var sm in subMesh_dict[m]) {
  84374. subMesh_obj = subMesh_dict[m][sm];
  84375. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84376. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84377. }
  84378. materialIndexOffset += ++materialMaxIndex;
  84379. }
  84380. }
  84381. return mesh;
  84382. };
  84383. // Build Mesh from CSG taking material and transforms into account
  84384. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84385. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84386. mesh.material = material;
  84387. mesh.position.copyFrom(this.position);
  84388. mesh.rotation.copyFrom(this.rotation);
  84389. if (this.rotationQuaternion) {
  84390. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84391. }
  84392. mesh.scaling.copyFrom(this.scaling);
  84393. mesh.computeWorldMatrix(true);
  84394. return mesh;
  84395. };
  84396. return CSG;
  84397. }());
  84398. BABYLON.CSG = CSG;
  84399. })(BABYLON || (BABYLON = {}));
  84400. //# sourceMappingURL=babylon.csg.js.map
  84401. var BABYLON;
  84402. (function (BABYLON) {
  84403. var LensFlare = /** @class */ (function () {
  84404. function LensFlare(size, position, color, imgUrl, system) {
  84405. this.size = size;
  84406. this.position = position;
  84407. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84408. this.color = color || new BABYLON.Color3(1, 1, 1);
  84409. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84410. this._system = system;
  84411. system.lensFlares.push(this);
  84412. }
  84413. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84414. return new LensFlare(size, position, color, imgUrl, system);
  84415. };
  84416. LensFlare.prototype.dispose = function () {
  84417. if (this.texture) {
  84418. this.texture.dispose();
  84419. }
  84420. // Remove from scene
  84421. var index = this._system.lensFlares.indexOf(this);
  84422. this._system.lensFlares.splice(index, 1);
  84423. };
  84424. ;
  84425. return LensFlare;
  84426. }());
  84427. BABYLON.LensFlare = LensFlare;
  84428. })(BABYLON || (BABYLON = {}));
  84429. //# sourceMappingURL=babylon.lensFlare.js.map
  84430. var BABYLON;
  84431. (function (BABYLON) {
  84432. // Adds the parser to the scene parsers.
  84433. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84434. // Lens flares
  84435. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84436. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84437. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84438. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84439. container.lensFlareSystems.push(lf);
  84440. }
  84441. }
  84442. });
  84443. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84444. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84445. if (this.lensFlareSystems[index].name === name) {
  84446. return this.lensFlareSystems[index];
  84447. }
  84448. }
  84449. return null;
  84450. };
  84451. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84452. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84453. if (this.lensFlareSystems[index].id === id) {
  84454. return this.lensFlareSystems[index];
  84455. }
  84456. }
  84457. return null;
  84458. };
  84459. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84460. var index = this.lensFlareSystems.indexOf(toRemove);
  84461. if (index !== -1) {
  84462. this.lensFlareSystems.splice(index, 1);
  84463. }
  84464. return index;
  84465. };
  84466. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84467. this.lensFlareSystems.push(newLensFlareSystem);
  84468. };
  84469. /**
  84470. * Defines the lens flare scene component responsible to manage any lens flares
  84471. * in a given scene.
  84472. */
  84473. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84474. /**
  84475. * Creates a new instance of the component for the given scene
  84476. * @param scene Defines the scene to register the component in
  84477. */
  84478. function LensFlareSystemSceneComponent(scene) {
  84479. /**
  84480. * The component name helpfull to identify the component in the list of scene components.
  84481. */
  84482. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84483. this.scene = scene;
  84484. scene.lensFlareSystems = new Array();
  84485. }
  84486. /**
  84487. * Registers the component in a given scene
  84488. */
  84489. LensFlareSystemSceneComponent.prototype.register = function () {
  84490. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84491. };
  84492. /**
  84493. * Rebuilds the elements related to this component in case of
  84494. * context lost for instance.
  84495. */
  84496. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84497. // Nothing to do for lens flare
  84498. };
  84499. /**
  84500. * Adds all the element from the container to the scene
  84501. * @param container the container holding the elements
  84502. */
  84503. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84504. var _this = this;
  84505. if (!container.lensFlareSystems) {
  84506. return;
  84507. }
  84508. container.lensFlareSystems.forEach(function (o) {
  84509. _this.scene.addLensFlareSystem(o);
  84510. });
  84511. };
  84512. /**
  84513. * Removes all the elements in the container from the scene
  84514. * @param container contains the elements to remove
  84515. */
  84516. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84517. var _this = this;
  84518. if (!container.lensFlareSystems) {
  84519. return;
  84520. }
  84521. container.lensFlareSystems.forEach(function (o) {
  84522. _this.scene.removeLensFlareSystem(o);
  84523. });
  84524. };
  84525. /**
  84526. * Serializes the component data to the specified json object
  84527. * @param serializationObject The object to serialize to
  84528. */
  84529. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84530. // Lens flares
  84531. serializationObject.lensFlareSystems = [];
  84532. var lensFlareSystems = this.scene.lensFlareSystems;
  84533. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84534. var lensFlareSystem = lensFlareSystems_1[_i];
  84535. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84536. }
  84537. };
  84538. /**
  84539. * Disposes the component and the associated ressources.
  84540. */
  84541. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84542. var lensFlareSystems = this.scene.lensFlareSystems;
  84543. while (lensFlareSystems.length) {
  84544. lensFlareSystems[0].dispose();
  84545. }
  84546. };
  84547. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84548. // Lens flares
  84549. if (this.scene.lensFlaresEnabled) {
  84550. var lensFlareSystems = this.scene.lensFlareSystems;
  84551. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84552. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84553. var lensFlareSystem = lensFlareSystems_2[_i];
  84554. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84555. lensFlareSystem.render();
  84556. }
  84557. }
  84558. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84559. }
  84560. };
  84561. return LensFlareSystemSceneComponent;
  84562. }());
  84563. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84564. })(BABYLON || (BABYLON = {}));
  84565. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84566. var BABYLON;
  84567. (function (BABYLON) {
  84568. var LensFlareSystem = /** @class */ (function () {
  84569. function LensFlareSystem(name, emitter, scene) {
  84570. this.name = name;
  84571. this.lensFlares = new Array();
  84572. this.borderLimit = 300;
  84573. this.viewportBorder = 0;
  84574. this.layerMask = 0x0FFFFFFF;
  84575. this._vertexBuffers = {};
  84576. this._isEnabled = true;
  84577. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84578. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84579. if (!component) {
  84580. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84581. scene._addComponent(component);
  84582. }
  84583. this._emitter = emitter;
  84584. this.id = name;
  84585. scene.lensFlareSystems.push(this);
  84586. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84587. var engine = scene.getEngine();
  84588. // VBO
  84589. var vertices = [];
  84590. vertices.push(1, 1);
  84591. vertices.push(-1, 1);
  84592. vertices.push(-1, -1);
  84593. vertices.push(1, -1);
  84594. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84595. // Indices
  84596. var indices = [];
  84597. indices.push(0);
  84598. indices.push(1);
  84599. indices.push(2);
  84600. indices.push(0);
  84601. indices.push(2);
  84602. indices.push(3);
  84603. this._indexBuffer = engine.createIndexBuffer(indices);
  84604. // Effects
  84605. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84606. }
  84607. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84608. get: function () {
  84609. return this._isEnabled;
  84610. },
  84611. set: function (value) {
  84612. this._isEnabled = value;
  84613. },
  84614. enumerable: true,
  84615. configurable: true
  84616. });
  84617. LensFlareSystem.prototype.getScene = function () {
  84618. return this._scene;
  84619. };
  84620. LensFlareSystem.prototype.getEmitter = function () {
  84621. return this._emitter;
  84622. };
  84623. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84624. this._emitter = newEmitter;
  84625. };
  84626. LensFlareSystem.prototype.getEmitterPosition = function () {
  84627. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84628. };
  84629. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84630. var position = this.getEmitterPosition();
  84631. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84632. this._positionX = position.x;
  84633. this._positionY = position.y;
  84634. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84635. if (this.viewportBorder > 0) {
  84636. globalViewport.x -= this.viewportBorder;
  84637. globalViewport.y -= this.viewportBorder;
  84638. globalViewport.width += this.viewportBorder * 2;
  84639. globalViewport.height += this.viewportBorder * 2;
  84640. position.x += this.viewportBorder;
  84641. position.y += this.viewportBorder;
  84642. this._positionX += this.viewportBorder;
  84643. this._positionY += this.viewportBorder;
  84644. }
  84645. if (position.z > 0) {
  84646. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84647. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84648. return true;
  84649. }
  84650. return true;
  84651. }
  84652. return false;
  84653. };
  84654. LensFlareSystem.prototype._isVisible = function () {
  84655. if (!this._isEnabled || !this._scene.activeCamera) {
  84656. return false;
  84657. }
  84658. var emitterPosition = this.getEmitterPosition();
  84659. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84660. var distance = direction.length();
  84661. direction.normalize();
  84662. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84663. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84664. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84665. };
  84666. LensFlareSystem.prototype.render = function () {
  84667. if (!this._effect.isReady() || !this._scene.activeCamera)
  84668. return false;
  84669. var engine = this._scene.getEngine();
  84670. var viewport = this._scene.activeCamera.viewport;
  84671. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84672. // Position
  84673. if (!this.computeEffectivePosition(globalViewport)) {
  84674. return false;
  84675. }
  84676. // Visibility
  84677. if (!this._isVisible()) {
  84678. return false;
  84679. }
  84680. // Intensity
  84681. var awayX;
  84682. var awayY;
  84683. if (this._positionX < this.borderLimit + globalViewport.x) {
  84684. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84685. }
  84686. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84687. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84688. }
  84689. else {
  84690. awayX = 0;
  84691. }
  84692. if (this._positionY < this.borderLimit + globalViewport.y) {
  84693. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84694. }
  84695. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84696. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84697. }
  84698. else {
  84699. awayY = 0;
  84700. }
  84701. var away = (awayX > awayY) ? awayX : awayY;
  84702. away -= this.viewportBorder;
  84703. if (away > this.borderLimit) {
  84704. away = this.borderLimit;
  84705. }
  84706. var intensity = 1.0 - (away / this.borderLimit);
  84707. if (intensity < 0) {
  84708. return false;
  84709. }
  84710. if (intensity > 1.0) {
  84711. intensity = 1.0;
  84712. }
  84713. if (this.viewportBorder > 0) {
  84714. globalViewport.x += this.viewportBorder;
  84715. globalViewport.y += this.viewportBorder;
  84716. globalViewport.width -= this.viewportBorder * 2;
  84717. globalViewport.height -= this.viewportBorder * 2;
  84718. this._positionX -= this.viewportBorder;
  84719. this._positionY -= this.viewportBorder;
  84720. }
  84721. // Position
  84722. var centerX = globalViewport.x + globalViewport.width / 2;
  84723. var centerY = globalViewport.y + globalViewport.height / 2;
  84724. var distX = centerX - this._positionX;
  84725. var distY = centerY - this._positionY;
  84726. // Effects
  84727. engine.enableEffect(this._effect);
  84728. engine.setState(false);
  84729. engine.setDepthBuffer(false);
  84730. // VBOs
  84731. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84732. // Flares
  84733. for (var index = 0; index < this.lensFlares.length; index++) {
  84734. var flare = this.lensFlares[index];
  84735. engine.setAlphaMode(flare.alphaMode);
  84736. var x = centerX - (distX * flare.position);
  84737. var y = centerY - (distY * flare.position);
  84738. var cw = flare.size;
  84739. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84740. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84741. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84742. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84743. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84744. // Texture
  84745. this._effect.setTexture("textureSampler", flare.texture);
  84746. // Color
  84747. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84748. // Draw order
  84749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84750. }
  84751. engine.setDepthBuffer(true);
  84752. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84753. return true;
  84754. };
  84755. LensFlareSystem.prototype.dispose = function () {
  84756. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84757. if (vertexBuffer) {
  84758. vertexBuffer.dispose();
  84759. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84760. }
  84761. if (this._indexBuffer) {
  84762. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84763. this._indexBuffer = null;
  84764. }
  84765. while (this.lensFlares.length) {
  84766. this.lensFlares[0].dispose();
  84767. }
  84768. // Remove from scene
  84769. var index = this._scene.lensFlareSystems.indexOf(this);
  84770. this._scene.lensFlareSystems.splice(index, 1);
  84771. };
  84772. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84773. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84774. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84775. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84776. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84777. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84778. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84779. var parsedFlare = parsedLensFlareSystem.flares[index];
  84780. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84781. }
  84782. return lensFlareSystem;
  84783. };
  84784. LensFlareSystem.prototype.serialize = function () {
  84785. var serializationObject = {};
  84786. serializationObject.id = this.id;
  84787. serializationObject.name = this.name;
  84788. serializationObject.emitterId = this.getEmitter().id;
  84789. serializationObject.borderLimit = this.borderLimit;
  84790. serializationObject.flares = [];
  84791. for (var index = 0; index < this.lensFlares.length; index++) {
  84792. var flare = this.lensFlares[index];
  84793. serializationObject.flares.push({
  84794. size: flare.size,
  84795. position: flare.position,
  84796. color: flare.color.asArray(),
  84797. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84798. });
  84799. }
  84800. return serializationObject;
  84801. };
  84802. return LensFlareSystem;
  84803. }());
  84804. BABYLON.LensFlareSystem = LensFlareSystem;
  84805. })(BABYLON || (BABYLON = {}));
  84806. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84807. var BABYLON;
  84808. (function (BABYLON) {
  84809. /**
  84810. * This is a holder class for the physics joint created by the physics plugin.
  84811. * It holds a set of functions to control the underlying joint.
  84812. */
  84813. var PhysicsJoint = /** @class */ (function () {
  84814. function PhysicsJoint(type, jointData) {
  84815. this.type = type;
  84816. this.jointData = jointData;
  84817. jointData.nativeParams = jointData.nativeParams || {};
  84818. }
  84819. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84820. get: function () {
  84821. return this._physicsJoint;
  84822. },
  84823. set: function (newJoint) {
  84824. if (this._physicsJoint) {
  84825. //remove from the wolrd
  84826. }
  84827. this._physicsJoint = newJoint;
  84828. },
  84829. enumerable: true,
  84830. configurable: true
  84831. });
  84832. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84833. set: function (physicsPlugin) {
  84834. this._physicsPlugin = physicsPlugin;
  84835. },
  84836. enumerable: true,
  84837. configurable: true
  84838. });
  84839. /**
  84840. * Execute a function that is physics-plugin specific.
  84841. * @param {Function} func the function that will be executed.
  84842. * It accepts two parameters: the physics world and the physics joint.
  84843. */
  84844. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84845. func(this._physicsPlugin.world, this._physicsJoint);
  84846. };
  84847. //TODO check if the native joints are the same
  84848. //Joint Types
  84849. PhysicsJoint.DistanceJoint = 0;
  84850. PhysicsJoint.HingeJoint = 1;
  84851. PhysicsJoint.BallAndSocketJoint = 2;
  84852. PhysicsJoint.WheelJoint = 3;
  84853. PhysicsJoint.SliderJoint = 4;
  84854. //OIMO
  84855. PhysicsJoint.PrismaticJoint = 5;
  84856. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84857. PhysicsJoint.UniversalJoint = 6;
  84858. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84859. //Cannon
  84860. //Similar to a Ball-Joint. Different in params
  84861. PhysicsJoint.PointToPointJoint = 8;
  84862. //Cannon only at the moment
  84863. PhysicsJoint.SpringJoint = 9;
  84864. PhysicsJoint.LockJoint = 10;
  84865. return PhysicsJoint;
  84866. }());
  84867. BABYLON.PhysicsJoint = PhysicsJoint;
  84868. /**
  84869. * A class representing a physics distance joint.
  84870. */
  84871. var DistanceJoint = /** @class */ (function (_super) {
  84872. __extends(DistanceJoint, _super);
  84873. function DistanceJoint(jointData) {
  84874. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84875. }
  84876. /**
  84877. * Update the predefined distance.
  84878. */
  84879. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84880. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84881. };
  84882. return DistanceJoint;
  84883. }(PhysicsJoint));
  84884. BABYLON.DistanceJoint = DistanceJoint;
  84885. var MotorEnabledJoint = /** @class */ (function (_super) {
  84886. __extends(MotorEnabledJoint, _super);
  84887. function MotorEnabledJoint(type, jointData) {
  84888. return _super.call(this, type, jointData) || this;
  84889. }
  84890. /**
  84891. * Set the motor values.
  84892. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84893. * @param {number} force the force to apply
  84894. * @param {number} maxForce max force for this motor.
  84895. */
  84896. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84897. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84898. };
  84899. /**
  84900. * Set the motor's limits.
  84901. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84902. */
  84903. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84904. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84905. };
  84906. return MotorEnabledJoint;
  84907. }(PhysicsJoint));
  84908. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84909. /**
  84910. * This class represents a single hinge physics joint
  84911. */
  84912. var HingeJoint = /** @class */ (function (_super) {
  84913. __extends(HingeJoint, _super);
  84914. function HingeJoint(jointData) {
  84915. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84916. }
  84917. /**
  84918. * Set the motor values.
  84919. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84920. * @param {number} force the force to apply
  84921. * @param {number} maxForce max force for this motor.
  84922. */
  84923. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84924. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84925. };
  84926. /**
  84927. * Set the motor's limits.
  84928. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84929. */
  84930. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84931. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84932. };
  84933. return HingeJoint;
  84934. }(MotorEnabledJoint));
  84935. BABYLON.HingeJoint = HingeJoint;
  84936. /**
  84937. * This class represents a dual hinge physics joint (same as wheel joint)
  84938. */
  84939. var Hinge2Joint = /** @class */ (function (_super) {
  84940. __extends(Hinge2Joint, _super);
  84941. function Hinge2Joint(jointData) {
  84942. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84943. }
  84944. /**
  84945. * Set the motor values.
  84946. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84947. * @param {number} force the force to apply
  84948. * @param {number} maxForce max force for this motor.
  84949. * @param {motorIndex} the motor's index, 0 or 1.
  84950. */
  84951. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84952. if (motorIndex === void 0) { motorIndex = 0; }
  84953. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84954. };
  84955. /**
  84956. * Set the motor limits.
  84957. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84958. * @param {number} upperLimit the upper limit
  84959. * @param {number} lowerLimit lower limit
  84960. * @param {motorIndex} the motor's index, 0 or 1.
  84961. */
  84962. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84963. if (motorIndex === void 0) { motorIndex = 0; }
  84964. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84965. };
  84966. return Hinge2Joint;
  84967. }(MotorEnabledJoint));
  84968. BABYLON.Hinge2Joint = Hinge2Joint;
  84969. })(BABYLON || (BABYLON = {}));
  84970. //# sourceMappingURL=babylon.physicsJoint.js.map
  84971. var BABYLON;
  84972. (function (BABYLON) {
  84973. var PhysicsImpostor = /** @class */ (function () {
  84974. function PhysicsImpostor(object, type, _options, _scene) {
  84975. if (_options === void 0) { _options = { mass: 0 }; }
  84976. var _this = this;
  84977. this.object = object;
  84978. this.type = type;
  84979. this._options = _options;
  84980. this._scene = _scene;
  84981. this._bodyUpdateRequired = false;
  84982. this._onBeforePhysicsStepCallbacks = new Array();
  84983. this._onAfterPhysicsStepCallbacks = new Array();
  84984. this._onPhysicsCollideCallbacks = [];
  84985. this._deltaPosition = BABYLON.Vector3.Zero();
  84986. this._isDisposed = false;
  84987. //temp variables for parent rotation calculations
  84988. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84989. this._tmpQuat = new BABYLON.Quaternion();
  84990. this._tmpQuat2 = new BABYLON.Quaternion();
  84991. /**
  84992. * this function is executed by the physics engine.
  84993. */
  84994. this.beforeStep = function () {
  84995. if (!_this._physicsEngine) {
  84996. return;
  84997. }
  84998. _this.object.translate(_this._deltaPosition, -1);
  84999. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  85000. _this.object.computeWorldMatrix(false);
  85001. if (_this.object.parent && _this.object.rotationQuaternion) {
  85002. _this.getParentsRotation();
  85003. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  85004. }
  85005. else {
  85006. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  85007. }
  85008. if (!_this._options.disableBidirectionalTransformation) {
  85009. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  85010. }
  85011. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  85012. func(_this);
  85013. });
  85014. };
  85015. /**
  85016. * this function is executed by the physics engine.
  85017. */
  85018. this.afterStep = function () {
  85019. if (!_this._physicsEngine) {
  85020. return;
  85021. }
  85022. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  85023. func(_this);
  85024. });
  85025. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  85026. // object has now its world rotation. needs to be converted to local.
  85027. if (_this.object.parent && _this.object.rotationQuaternion) {
  85028. _this.getParentsRotation();
  85029. _this._tmpQuat.conjugateInPlace();
  85030. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  85031. }
  85032. // take the position set and make it the absolute position of this object.
  85033. _this.object.setAbsolutePosition(_this.object.position);
  85034. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  85035. _this.object.translate(_this._deltaPosition, 1);
  85036. };
  85037. /**
  85038. * Legacy collision detection event support
  85039. */
  85040. this.onCollideEvent = null;
  85041. //event and body object due to cannon's event-based architecture.
  85042. this.onCollide = function (e) {
  85043. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  85044. return;
  85045. }
  85046. if (!_this._physicsEngine) {
  85047. return;
  85048. }
  85049. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  85050. if (otherImpostor) {
  85051. // Legacy collision detection event support
  85052. if (_this.onCollideEvent) {
  85053. _this.onCollideEvent(_this, otherImpostor);
  85054. }
  85055. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  85056. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  85057. }).forEach(function (obj) {
  85058. obj.callback(_this, otherImpostor);
  85059. });
  85060. }
  85061. };
  85062. //sanity check!
  85063. if (!this.object) {
  85064. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  85065. return;
  85066. }
  85067. //legacy support for old syntax.
  85068. if (!this._scene && object.getScene) {
  85069. this._scene = object.getScene();
  85070. }
  85071. if (!this._scene) {
  85072. return;
  85073. }
  85074. this._physicsEngine = this._scene.getPhysicsEngine();
  85075. if (!this._physicsEngine) {
  85076. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  85077. }
  85078. else {
  85079. //set the object's quaternion, if not set
  85080. if (!this.object.rotationQuaternion) {
  85081. if (this.object.rotation) {
  85082. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  85083. }
  85084. else {
  85085. this.object.rotationQuaternion = new BABYLON.Quaternion();
  85086. }
  85087. }
  85088. //default options params
  85089. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  85090. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  85091. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  85092. this._joints = [];
  85093. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  85094. if (!this.object.parent || this._options.ignoreParent) {
  85095. this._init();
  85096. }
  85097. else if (this.object.parent.physicsImpostor) {
  85098. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  85099. }
  85100. }
  85101. }
  85102. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  85103. get: function () {
  85104. return this._isDisposed;
  85105. },
  85106. enumerable: true,
  85107. configurable: true
  85108. });
  85109. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  85110. get: function () {
  85111. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  85112. },
  85113. set: function (value) {
  85114. this.setMass(value);
  85115. },
  85116. enumerable: true,
  85117. configurable: true
  85118. });
  85119. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  85120. get: function () {
  85121. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  85122. },
  85123. set: function (value) {
  85124. if (!this._physicsEngine) {
  85125. return;
  85126. }
  85127. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  85128. },
  85129. enumerable: true,
  85130. configurable: true
  85131. });
  85132. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  85133. get: function () {
  85134. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  85135. },
  85136. set: function (value) {
  85137. if (!this._physicsEngine) {
  85138. return;
  85139. }
  85140. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  85141. },
  85142. enumerable: true,
  85143. configurable: true
  85144. });
  85145. /**
  85146. * This function will completly initialize this impostor.
  85147. * It will create a new body - but only if this mesh has no parent.
  85148. * If it has, this impostor will not be used other than to define the impostor
  85149. * of the child mesh.
  85150. */
  85151. PhysicsImpostor.prototype._init = function () {
  85152. if (!this._physicsEngine) {
  85153. return;
  85154. }
  85155. this._physicsEngine.removeImpostor(this);
  85156. this.physicsBody = null;
  85157. this._parent = this._parent || this._getPhysicsParent();
  85158. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  85159. this._physicsEngine.addImpostor(this);
  85160. }
  85161. };
  85162. PhysicsImpostor.prototype._getPhysicsParent = function () {
  85163. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  85164. var parentMesh = this.object.parent;
  85165. return parentMesh.physicsImpostor;
  85166. }
  85167. return null;
  85168. };
  85169. /**
  85170. * Should a new body be generated.
  85171. */
  85172. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  85173. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  85174. };
  85175. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  85176. this.forceUpdate();
  85177. };
  85178. /**
  85179. * Force a regeneration of this or the parent's impostor's body.
  85180. * Use under cautious - This will remove all joints already implemented.
  85181. */
  85182. PhysicsImpostor.prototype.forceUpdate = function () {
  85183. this._init();
  85184. if (this.parent && !this._options.ignoreParent) {
  85185. this.parent.forceUpdate();
  85186. }
  85187. };
  85188. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  85189. /*public get mesh(): AbstractMesh {
  85190. return this._mesh;
  85191. }*/
  85192. /**
  85193. * Gets the body that holds this impostor. Either its own, or its parent.
  85194. */
  85195. get: function () {
  85196. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  85197. },
  85198. /**
  85199. * Set the physics body. Used mainly by the physics engine/plugin
  85200. */
  85201. set: function (physicsBody) {
  85202. if (this._physicsBody && this._physicsEngine) {
  85203. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  85204. }
  85205. this._physicsBody = physicsBody;
  85206. this.resetUpdateFlags();
  85207. },
  85208. enumerable: true,
  85209. configurable: true
  85210. });
  85211. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  85212. get: function () {
  85213. return !this._options.ignoreParent && this._parent ? this._parent : null;
  85214. },
  85215. set: function (value) {
  85216. this._parent = value;
  85217. },
  85218. enumerable: true,
  85219. configurable: true
  85220. });
  85221. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  85222. this._bodyUpdateRequired = false;
  85223. };
  85224. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  85225. if (this.object.getBoundingInfo) {
  85226. var q = this.object.rotationQuaternion;
  85227. //reset rotation
  85228. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  85229. //calculate the world matrix with no rotation
  85230. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85231. var boundingInfo = this.object.getBoundingInfo();
  85232. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  85233. //bring back the rotation
  85234. this.object.rotationQuaternion = q;
  85235. //calculate the world matrix with the new rotation
  85236. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  85237. return size;
  85238. }
  85239. else {
  85240. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  85241. }
  85242. };
  85243. PhysicsImpostor.prototype.getObjectCenter = function () {
  85244. if (this.object.getBoundingInfo) {
  85245. var boundingInfo = this.object.getBoundingInfo();
  85246. return boundingInfo.boundingBox.centerWorld;
  85247. }
  85248. else {
  85249. return this.object.position;
  85250. }
  85251. };
  85252. /**
  85253. * Get a specific parametes from the options parameter.
  85254. */
  85255. PhysicsImpostor.prototype.getParam = function (paramName) {
  85256. return this._options[paramName];
  85257. };
  85258. /**
  85259. * Sets a specific parameter in the options given to the physics plugin
  85260. */
  85261. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85262. this._options[paramName] = value;
  85263. this._bodyUpdateRequired = true;
  85264. };
  85265. /**
  85266. * Specifically change the body's mass option. Won't recreate the physics body object
  85267. */
  85268. PhysicsImpostor.prototype.setMass = function (mass) {
  85269. if (this.getParam("mass") !== mass) {
  85270. this.setParam("mass", mass);
  85271. }
  85272. if (this._physicsEngine) {
  85273. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85274. }
  85275. };
  85276. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85277. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85278. };
  85279. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85280. if (this._physicsEngine) {
  85281. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85282. }
  85283. };
  85284. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85285. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85286. };
  85287. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85288. if (this._physicsEngine) {
  85289. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85290. }
  85291. };
  85292. /**
  85293. * Execute a function with the physics plugin native code.
  85294. * Provide a function the will have two variables - the world object and the physics body object.
  85295. */
  85296. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85297. if (this._physicsEngine) {
  85298. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85299. }
  85300. };
  85301. /**
  85302. * Register a function that will be executed before the physics world is stepping forward.
  85303. */
  85304. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85305. this._onBeforePhysicsStepCallbacks.push(func);
  85306. };
  85307. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85308. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85309. if (index > -1) {
  85310. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85311. }
  85312. else {
  85313. BABYLON.Tools.Warn("Function to remove was not found");
  85314. }
  85315. };
  85316. /**
  85317. * Register a function that will be executed after the physics step
  85318. */
  85319. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85320. this._onAfterPhysicsStepCallbacks.push(func);
  85321. };
  85322. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85323. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85324. if (index > -1) {
  85325. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85326. }
  85327. else {
  85328. BABYLON.Tools.Warn("Function to remove was not found");
  85329. }
  85330. };
  85331. /**
  85332. * register a function that will be executed when this impostor collides against a different body.
  85333. */
  85334. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85335. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85336. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85337. };
  85338. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85339. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85340. var index = -1;
  85341. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85342. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85343. // chcek the arrays match
  85344. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85345. return collidedAgainstList.indexOf(impostor) > -1;
  85346. });
  85347. if (sameList) {
  85348. index = idx;
  85349. }
  85350. return sameList;
  85351. }
  85352. return false;
  85353. });
  85354. if (found) {
  85355. this._onPhysicsCollideCallbacks.splice(index, 1);
  85356. }
  85357. else {
  85358. BABYLON.Tools.Warn("Function to remove was not found");
  85359. }
  85360. };
  85361. PhysicsImpostor.prototype.getParentsRotation = function () {
  85362. var parent = this.object.parent;
  85363. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85364. while (parent) {
  85365. if (parent.rotationQuaternion) {
  85366. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85367. }
  85368. else {
  85369. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85370. }
  85371. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85372. parent = parent.parent;
  85373. }
  85374. return this._tmpQuat;
  85375. };
  85376. /**
  85377. * Apply a force
  85378. */
  85379. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85380. if (this._physicsEngine) {
  85381. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85382. }
  85383. return this;
  85384. };
  85385. /**
  85386. * Apply an impulse
  85387. */
  85388. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85389. if (this._physicsEngine) {
  85390. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85391. }
  85392. return this;
  85393. };
  85394. /**
  85395. * A help function to create a joint.
  85396. */
  85397. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85398. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85399. this.addJoint(otherImpostor, joint);
  85400. return this;
  85401. };
  85402. /**
  85403. * Add a joint to this impostor with a different impostor.
  85404. */
  85405. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85406. this._joints.push({
  85407. otherImpostor: otherImpostor,
  85408. joint: joint
  85409. });
  85410. if (this._physicsEngine) {
  85411. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85412. }
  85413. return this;
  85414. };
  85415. /**
  85416. * Will keep this body still, in a sleep mode.
  85417. */
  85418. PhysicsImpostor.prototype.sleep = function () {
  85419. if (this._physicsEngine) {
  85420. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85421. }
  85422. return this;
  85423. };
  85424. /**
  85425. * Wake the body up.
  85426. */
  85427. PhysicsImpostor.prototype.wakeUp = function () {
  85428. if (this._physicsEngine) {
  85429. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85430. }
  85431. return this;
  85432. };
  85433. PhysicsImpostor.prototype.clone = function (newObject) {
  85434. if (!newObject)
  85435. return null;
  85436. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85437. };
  85438. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85439. var _this = this;
  85440. //no dispose if no physics engine is available.
  85441. if (!this._physicsEngine) {
  85442. return;
  85443. }
  85444. this._joints.forEach(function (j) {
  85445. if (_this._physicsEngine) {
  85446. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85447. }
  85448. });
  85449. //dispose the physics body
  85450. this._physicsEngine.removeImpostor(this);
  85451. if (this.parent) {
  85452. this.parent.forceUpdate();
  85453. }
  85454. else {
  85455. /*this._object.getChildMeshes().forEach(function(mesh) {
  85456. if (mesh.physicsImpostor) {
  85457. if (disposeChildren) {
  85458. mesh.physicsImpostor.dispose();
  85459. mesh.physicsImpostor = null;
  85460. }
  85461. }
  85462. })*/
  85463. }
  85464. this._isDisposed = true;
  85465. };
  85466. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85467. this._deltaPosition.copyFrom(position);
  85468. };
  85469. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85470. if (!this._deltaRotation) {
  85471. this._deltaRotation = new BABYLON.Quaternion();
  85472. }
  85473. this._deltaRotation.copyFrom(rotation);
  85474. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85475. };
  85476. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85477. if (this._physicsEngine) {
  85478. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85479. }
  85480. return this;
  85481. };
  85482. PhysicsImpostor.prototype.getRadius = function () {
  85483. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85484. };
  85485. /**
  85486. * Sync a bone with this impostor
  85487. * @param bone The bone to sync to the impostor.
  85488. * @param boneMesh The mesh that the bone is influencing.
  85489. * @param jointPivot The pivot of the joint / bone in local space.
  85490. * @param distToJoint Optional distance from the impostor to the joint.
  85491. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85492. */
  85493. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85494. var tempVec = PhysicsImpostor._tmpVecs[0];
  85495. var mesh = this.object;
  85496. if (mesh.rotationQuaternion) {
  85497. if (adjustRotation) {
  85498. var tempQuat = PhysicsImpostor._tmpQuat;
  85499. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85500. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85501. }
  85502. else {
  85503. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85504. }
  85505. }
  85506. tempVec.x = 0;
  85507. tempVec.y = 0;
  85508. tempVec.z = 0;
  85509. if (jointPivot) {
  85510. tempVec.x = jointPivot.x;
  85511. tempVec.y = jointPivot.y;
  85512. tempVec.z = jointPivot.z;
  85513. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85514. if (distToJoint === undefined || distToJoint === null) {
  85515. distToJoint = jointPivot.length();
  85516. }
  85517. tempVec.x *= distToJoint;
  85518. tempVec.y *= distToJoint;
  85519. tempVec.z *= distToJoint;
  85520. }
  85521. if (bone.getParent()) {
  85522. tempVec.addInPlace(mesh.getAbsolutePosition());
  85523. bone.setAbsolutePosition(tempVec, boneMesh);
  85524. }
  85525. else {
  85526. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85527. boneMesh.position.x -= tempVec.x;
  85528. boneMesh.position.y -= tempVec.y;
  85529. boneMesh.position.z -= tempVec.z;
  85530. }
  85531. };
  85532. /**
  85533. * Sync impostor to a bone
  85534. * @param bone The bone that the impostor will be synced to.
  85535. * @param boneMesh The mesh that the bone is influencing.
  85536. * @param jointPivot The pivot of the joint / bone in local space.
  85537. * @param distToJoint Optional distance from the impostor to the joint.
  85538. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85539. * @param boneAxis Optional vector3 axis the bone is aligned with
  85540. */
  85541. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85542. var mesh = this.object;
  85543. if (mesh.rotationQuaternion) {
  85544. if (adjustRotation) {
  85545. var tempQuat = PhysicsImpostor._tmpQuat;
  85546. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85547. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85548. }
  85549. else {
  85550. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85551. }
  85552. }
  85553. var pos = PhysicsImpostor._tmpVecs[0];
  85554. var boneDir = PhysicsImpostor._tmpVecs[1];
  85555. if (!boneAxis) {
  85556. boneAxis = PhysicsImpostor._tmpVecs[2];
  85557. boneAxis.x = 0;
  85558. boneAxis.y = 1;
  85559. boneAxis.z = 0;
  85560. }
  85561. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85562. bone.getAbsolutePositionToRef(boneMesh, pos);
  85563. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85564. distToJoint = jointPivot.length();
  85565. }
  85566. if (distToJoint !== undefined && distToJoint !== null) {
  85567. pos.x += boneDir.x * distToJoint;
  85568. pos.y += boneDir.y * distToJoint;
  85569. pos.z += boneDir.z * distToJoint;
  85570. }
  85571. mesh.setAbsolutePosition(pos);
  85572. };
  85573. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85574. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85575. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85576. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85577. //Impostor types
  85578. PhysicsImpostor.NoImpostor = 0;
  85579. PhysicsImpostor.SphereImpostor = 1;
  85580. PhysicsImpostor.BoxImpostor = 2;
  85581. PhysicsImpostor.PlaneImpostor = 3;
  85582. PhysicsImpostor.MeshImpostor = 4;
  85583. PhysicsImpostor.CylinderImpostor = 7;
  85584. PhysicsImpostor.ParticleImpostor = 8;
  85585. PhysicsImpostor.HeightmapImpostor = 9;
  85586. return PhysicsImpostor;
  85587. }());
  85588. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85589. })(BABYLON || (BABYLON = {}));
  85590. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85591. var BABYLON;
  85592. (function (BABYLON) {
  85593. var PhysicsEngine = /** @class */ (function () {
  85594. function PhysicsEngine(gravity, _physicsPlugin) {
  85595. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85596. this._physicsPlugin = _physicsPlugin;
  85597. //new methods and parameters
  85598. this._impostors = [];
  85599. this._joints = [];
  85600. if (!this._physicsPlugin.isSupported()) {
  85601. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85602. + "Please make sure it is included.");
  85603. }
  85604. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85605. this.setGravity(gravity);
  85606. this.setTimeStep();
  85607. }
  85608. PhysicsEngine.prototype.setGravity = function (gravity) {
  85609. this.gravity = gravity;
  85610. this._physicsPlugin.setGravity(this.gravity);
  85611. };
  85612. /**
  85613. * Set the time step of the physics engine.
  85614. * default is 1/60.
  85615. * To slow it down, enter 1/600 for example.
  85616. * To speed it up, 1/30
  85617. * @param {number} newTimeStep the new timestep to apply to this world.
  85618. */
  85619. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85620. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85621. this._physicsPlugin.setTimeStep(newTimeStep);
  85622. };
  85623. /**
  85624. * Get the time step of the physics engine.
  85625. */
  85626. PhysicsEngine.prototype.getTimeStep = function () {
  85627. return this._physicsPlugin.getTimeStep();
  85628. };
  85629. PhysicsEngine.prototype.dispose = function () {
  85630. this._impostors.forEach(function (impostor) {
  85631. impostor.dispose();
  85632. });
  85633. this._physicsPlugin.dispose();
  85634. };
  85635. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85636. return this._physicsPlugin.name;
  85637. };
  85638. /**
  85639. * Adding a new impostor for the impostor tracking.
  85640. * This will be done by the impostor itself.
  85641. * @param {PhysicsImpostor} impostor the impostor to add
  85642. */
  85643. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85644. impostor.uniqueId = this._impostors.push(impostor);
  85645. //if no parent, generate the body
  85646. if (!impostor.parent) {
  85647. this._physicsPlugin.generatePhysicsBody(impostor);
  85648. }
  85649. };
  85650. /**
  85651. * Remove an impostor from the engine.
  85652. * This impostor and its mesh will not longer be updated by the physics engine.
  85653. * @param {PhysicsImpostor} impostor the impostor to remove
  85654. */
  85655. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85656. var index = this._impostors.indexOf(impostor);
  85657. if (index > -1) {
  85658. var removed = this._impostors.splice(index, 1);
  85659. //Is it needed?
  85660. if (removed.length) {
  85661. //this will also remove it from the world.
  85662. removed[0].physicsBody = null;
  85663. }
  85664. }
  85665. };
  85666. /**
  85667. * Add a joint to the physics engine
  85668. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85669. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85670. * @param {PhysicsJoint} the joint that will connect both impostors.
  85671. */
  85672. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85673. var impostorJoint = {
  85674. mainImpostor: mainImpostor,
  85675. connectedImpostor: connectedImpostor,
  85676. joint: joint
  85677. };
  85678. joint.physicsPlugin = this._physicsPlugin;
  85679. this._joints.push(impostorJoint);
  85680. this._physicsPlugin.generateJoint(impostorJoint);
  85681. };
  85682. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85683. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85684. return (impostorJoint.connectedImpostor === connectedImpostor
  85685. && impostorJoint.joint === joint
  85686. && impostorJoint.mainImpostor === mainImpostor);
  85687. });
  85688. if (matchingJoints.length) {
  85689. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85690. //TODO remove it from the list as well
  85691. }
  85692. };
  85693. /**
  85694. * Called by the scene. no need to call it.
  85695. */
  85696. PhysicsEngine.prototype._step = function (delta) {
  85697. var _this = this;
  85698. //check if any mesh has no body / requires an update
  85699. this._impostors.forEach(function (impostor) {
  85700. if (impostor.isBodyInitRequired()) {
  85701. _this._physicsPlugin.generatePhysicsBody(impostor);
  85702. }
  85703. });
  85704. if (delta > 0.1) {
  85705. delta = 0.1;
  85706. }
  85707. else if (delta <= 0) {
  85708. delta = 1.0 / 60.0;
  85709. }
  85710. this._physicsPlugin.executeStep(delta, this._impostors);
  85711. };
  85712. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85713. return this._physicsPlugin;
  85714. };
  85715. PhysicsEngine.prototype.getImpostors = function () {
  85716. return this._impostors;
  85717. };
  85718. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85719. for (var i = 0; i < this._impostors.length; ++i) {
  85720. if (this._impostors[i].object === object) {
  85721. return this._impostors[i];
  85722. }
  85723. }
  85724. return null;
  85725. };
  85726. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85727. for (var i = 0; i < this._impostors.length; ++i) {
  85728. if (this._impostors[i].physicsBody === body) {
  85729. return this._impostors[i];
  85730. }
  85731. }
  85732. return null;
  85733. };
  85734. // Statics
  85735. PhysicsEngine.Epsilon = 0.001;
  85736. return PhysicsEngine;
  85737. }());
  85738. BABYLON.PhysicsEngine = PhysicsEngine;
  85739. })(BABYLON || (BABYLON = {}));
  85740. //# sourceMappingURL=babylon.physicsEngine.js.map
  85741. var BABYLON;
  85742. (function (BABYLON) {
  85743. var PhysicsHelper = /** @class */ (function () {
  85744. function PhysicsHelper(scene) {
  85745. this._scene = scene;
  85746. this._physicsEngine = this._scene.getPhysicsEngine();
  85747. if (!this._physicsEngine) {
  85748. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85749. }
  85750. }
  85751. /**
  85752. * @param {Vector3} origin the origin of the explosion
  85753. * @param {number} radius the explosion radius
  85754. * @param {number} strength the explosion strength
  85755. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85756. */
  85757. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85758. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85759. if (!this._physicsEngine) {
  85760. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85761. return null;
  85762. }
  85763. var impostors = this._physicsEngine.getImpostors();
  85764. if (impostors.length === 0) {
  85765. return null;
  85766. }
  85767. var event = new PhysicsRadialExplosionEvent(this._scene);
  85768. impostors.forEach(function (impostor) {
  85769. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85770. if (!impostorForceAndContactPoint) {
  85771. return;
  85772. }
  85773. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85774. });
  85775. event.dispose(false);
  85776. return event;
  85777. };
  85778. /**
  85779. * @param {Vector3} origin the origin of the explosion
  85780. * @param {number} radius the explosion radius
  85781. * @param {number} strength the explosion strength
  85782. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85783. */
  85784. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85785. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85786. if (!this._physicsEngine) {
  85787. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85788. return null;
  85789. }
  85790. var impostors = this._physicsEngine.getImpostors();
  85791. if (impostors.length === 0) {
  85792. return null;
  85793. }
  85794. var event = new PhysicsRadialExplosionEvent(this._scene);
  85795. impostors.forEach(function (impostor) {
  85796. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85797. if (!impostorForceAndContactPoint) {
  85798. return;
  85799. }
  85800. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85801. });
  85802. event.dispose(false);
  85803. return event;
  85804. };
  85805. /**
  85806. * @param {Vector3} origin the origin of the explosion
  85807. * @param {number} radius the explosion radius
  85808. * @param {number} strength the explosion strength
  85809. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85810. */
  85811. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85812. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85813. if (!this._physicsEngine) {
  85814. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85815. return null;
  85816. }
  85817. var impostors = this._physicsEngine.getImpostors();
  85818. if (impostors.length === 0) {
  85819. return null;
  85820. }
  85821. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85822. event.dispose(false);
  85823. return event;
  85824. };
  85825. /**
  85826. * @param {Vector3} origin the origin of the updraft
  85827. * @param {number} radius the radius of the updraft
  85828. * @param {number} strength the strength of the updraft
  85829. * @param {number} height the height of the updraft
  85830. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85831. */
  85832. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85833. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85834. if (!this._physicsEngine) {
  85835. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85836. return null;
  85837. }
  85838. if (this._physicsEngine.getImpostors().length === 0) {
  85839. return null;
  85840. }
  85841. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85842. event.dispose(false);
  85843. return event;
  85844. };
  85845. /**
  85846. * @param {Vector3} origin the of the vortex
  85847. * @param {number} radius the radius of the vortex
  85848. * @param {number} strength the strength of the vortex
  85849. * @param {number} height the height of the vortex
  85850. */
  85851. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85852. if (!this._physicsEngine) {
  85853. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85854. return null;
  85855. }
  85856. if (this._physicsEngine.getImpostors().length === 0) {
  85857. return null;
  85858. }
  85859. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85860. event.dispose(false);
  85861. return event;
  85862. };
  85863. return PhysicsHelper;
  85864. }());
  85865. BABYLON.PhysicsHelper = PhysicsHelper;
  85866. /***** Radial explosion *****/
  85867. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85868. function PhysicsRadialExplosionEvent(scene) {
  85869. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85870. this._rays = [];
  85871. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85872. this._scene = scene;
  85873. }
  85874. /**
  85875. * Returns the data related to the radial explosion event (sphere & rays).
  85876. * @returns {PhysicsRadialExplosionEventData}
  85877. */
  85878. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85879. this._dataFetched = true;
  85880. return {
  85881. sphere: this._sphere,
  85882. rays: this._rays,
  85883. };
  85884. };
  85885. /**
  85886. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85887. * @param impostor
  85888. * @param {Vector3} origin the origin of the explosion
  85889. * @param {number} radius the explosion radius
  85890. * @param {number} strength the explosion strength
  85891. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85892. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85893. */
  85894. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85895. if (impostor.mass === 0) {
  85896. return null;
  85897. }
  85898. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85899. return null;
  85900. }
  85901. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85902. return null;
  85903. }
  85904. var impostorObjectCenter = impostor.getObjectCenter();
  85905. var direction = impostorObjectCenter.subtract(origin);
  85906. var ray = new BABYLON.Ray(origin, direction, radius);
  85907. this._rays.push(ray);
  85908. var hit = ray.intersectsMesh(impostor.object);
  85909. var contactPoint = hit.pickedPoint;
  85910. if (!contactPoint) {
  85911. return null;
  85912. }
  85913. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85914. if (distanceFromOrigin > radius) {
  85915. return null;
  85916. }
  85917. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85918. ? strength
  85919. : strength * (1 - (distanceFromOrigin / radius));
  85920. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85921. return { force: force, contactPoint: contactPoint };
  85922. };
  85923. /**
  85924. * Disposes the sphere.
  85925. * @param {bolean} force
  85926. */
  85927. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85928. var _this = this;
  85929. if (force === void 0) { force = true; }
  85930. if (force) {
  85931. this._sphere.dispose();
  85932. }
  85933. else {
  85934. setTimeout(function () {
  85935. if (!_this._dataFetched) {
  85936. _this._sphere.dispose();
  85937. }
  85938. }, 0);
  85939. }
  85940. };
  85941. /*** Helpers ***/
  85942. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85943. if (!this._sphere) {
  85944. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85945. this._sphere.isVisible = false;
  85946. }
  85947. };
  85948. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85949. var impostorObject = impostor.object;
  85950. this._prepareSphere();
  85951. this._sphere.position = origin;
  85952. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85953. this._sphere._updateBoundingInfo();
  85954. this._sphere.computeWorldMatrix(true);
  85955. return this._sphere.intersectsMesh(impostorObject, true);
  85956. };
  85957. return PhysicsRadialExplosionEvent;
  85958. }());
  85959. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85960. /***** Gravitational Field *****/
  85961. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85962. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85963. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85964. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85965. this._physicsHelper = physicsHelper;
  85966. this._scene = scene;
  85967. this._origin = origin;
  85968. this._radius = radius;
  85969. this._strength = strength;
  85970. this._falloff = falloff;
  85971. this._tickCallback = this._tick.bind(this);
  85972. }
  85973. /**
  85974. * Returns the data related to the gravitational field event (sphere).
  85975. * @returns {PhysicsGravitationalFieldEventData}
  85976. */
  85977. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85978. this._dataFetched = true;
  85979. return {
  85980. sphere: this._sphere,
  85981. };
  85982. };
  85983. /**
  85984. * Enables the gravitational field.
  85985. */
  85986. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85987. this._tickCallback.call(this);
  85988. this._scene.registerBeforeRender(this._tickCallback);
  85989. };
  85990. /**
  85991. * Disables the gravitational field.
  85992. */
  85993. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85994. this._scene.unregisterBeforeRender(this._tickCallback);
  85995. };
  85996. /**
  85997. * Disposes the sphere.
  85998. * @param {bolean} force
  85999. */
  86000. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  86001. var _this = this;
  86002. if (force === void 0) { force = true; }
  86003. if (force) {
  86004. this._sphere.dispose();
  86005. }
  86006. else {
  86007. setTimeout(function () {
  86008. if (!_this._dataFetched) {
  86009. _this._sphere.dispose();
  86010. }
  86011. }, 0);
  86012. }
  86013. };
  86014. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  86015. // Since the params won't change, we fetch the event only once
  86016. if (this._sphere) {
  86017. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86018. }
  86019. else {
  86020. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  86021. if (radialExplosionEvent) {
  86022. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  86023. }
  86024. }
  86025. };
  86026. return PhysicsGravitationalFieldEvent;
  86027. }());
  86028. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  86029. /***** Updraft *****/
  86030. var PhysicsUpdraftEvent = /** @class */ (function () {
  86031. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  86032. this._scene = _scene;
  86033. this._origin = _origin;
  86034. this._radius = _radius;
  86035. this._strength = _strength;
  86036. this._height = _height;
  86037. this._updraftMode = _updraftMode;
  86038. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86039. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  86040. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86041. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86042. this._physicsEngine = this._scene.getPhysicsEngine();
  86043. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86044. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86045. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86046. this._originDirection = this._origin.subtract(this._originTop).normalize();
  86047. }
  86048. this._tickCallback = this._tick.bind(this);
  86049. }
  86050. /**
  86051. * Returns the data related to the updraft event (cylinder).
  86052. * @returns {PhysicsUpdraftEventData}
  86053. */
  86054. PhysicsUpdraftEvent.prototype.getData = function () {
  86055. this._dataFetched = true;
  86056. return {
  86057. cylinder: this._cylinder,
  86058. };
  86059. };
  86060. /**
  86061. * Enables the updraft.
  86062. */
  86063. PhysicsUpdraftEvent.prototype.enable = function () {
  86064. this._tickCallback.call(this);
  86065. this._scene.registerBeforeRender(this._tickCallback);
  86066. };
  86067. /**
  86068. * Disables the cortex.
  86069. */
  86070. PhysicsUpdraftEvent.prototype.disable = function () {
  86071. this._scene.unregisterBeforeRender(this._tickCallback);
  86072. };
  86073. /**
  86074. * Disposes the sphere.
  86075. * @param {bolean} force
  86076. */
  86077. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  86078. var _this = this;
  86079. if (force === void 0) { force = true; }
  86080. if (force) {
  86081. this._cylinder.dispose();
  86082. }
  86083. else {
  86084. setTimeout(function () {
  86085. if (!_this._dataFetched) {
  86086. _this._cylinder.dispose();
  86087. }
  86088. }, 0);
  86089. }
  86090. };
  86091. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86092. if (impostor.mass === 0) {
  86093. return null;
  86094. }
  86095. if (!this._intersectsWithCylinder(impostor)) {
  86096. return null;
  86097. }
  86098. var impostorObjectCenter = impostor.getObjectCenter();
  86099. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  86100. var direction = this._originDirection;
  86101. }
  86102. else {
  86103. var direction = impostorObjectCenter.subtract(this._originTop);
  86104. }
  86105. var multiplier = this._strength * -1;
  86106. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  86107. return { force: force, contactPoint: impostorObjectCenter };
  86108. };
  86109. PhysicsUpdraftEvent.prototype._tick = function () {
  86110. var _this = this;
  86111. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86112. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86113. if (!impostorForceAndContactPoint) {
  86114. return;
  86115. }
  86116. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86117. });
  86118. };
  86119. /*** Helpers ***/
  86120. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  86121. if (!this._cylinder) {
  86122. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  86123. height: this._height,
  86124. diameter: this._radius * 2,
  86125. }, this._scene);
  86126. this._cylinder.isVisible = false;
  86127. }
  86128. };
  86129. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  86130. var impostorObject = impostor.object;
  86131. this._prepareCylinder();
  86132. this._cylinder.position = this._cylinderPosition;
  86133. return this._cylinder.intersectsMesh(impostorObject, true);
  86134. };
  86135. return PhysicsUpdraftEvent;
  86136. }());
  86137. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  86138. /***** Vortex *****/
  86139. var PhysicsVortexEvent = /** @class */ (function () {
  86140. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  86141. this._scene = _scene;
  86142. this._origin = _origin;
  86143. this._radius = _radius;
  86144. this._strength = _strength;
  86145. this._height = _height;
  86146. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  86147. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  86148. this._updraftMultiplier = 0.02;
  86149. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  86150. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  86151. this._physicsEngine = this._scene.getPhysicsEngine();
  86152. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  86153. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  86154. this._tickCallback = this._tick.bind(this);
  86155. }
  86156. /**
  86157. * Returns the data related to the vortex event (cylinder).
  86158. * @returns {PhysicsVortexEventData}
  86159. */
  86160. PhysicsVortexEvent.prototype.getData = function () {
  86161. this._dataFetched = true;
  86162. return {
  86163. cylinder: this._cylinder,
  86164. };
  86165. };
  86166. /**
  86167. * Enables the vortex.
  86168. */
  86169. PhysicsVortexEvent.prototype.enable = function () {
  86170. this._tickCallback.call(this);
  86171. this._scene.registerBeforeRender(this._tickCallback);
  86172. };
  86173. /**
  86174. * Disables the cortex.
  86175. */
  86176. PhysicsVortexEvent.prototype.disable = function () {
  86177. this._scene.unregisterBeforeRender(this._tickCallback);
  86178. };
  86179. /**
  86180. * Disposes the sphere.
  86181. * @param {bolean} force
  86182. */
  86183. PhysicsVortexEvent.prototype.dispose = function (force) {
  86184. var _this = this;
  86185. if (force === void 0) { force = true; }
  86186. if (force) {
  86187. this._cylinder.dispose();
  86188. }
  86189. else {
  86190. setTimeout(function () {
  86191. if (!_this._dataFetched) {
  86192. _this._cylinder.dispose();
  86193. }
  86194. }, 0);
  86195. }
  86196. };
  86197. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  86198. if (impostor.mass === 0) {
  86199. return null;
  86200. }
  86201. if (!this._intersectsWithCylinder(impostor)) {
  86202. return null;
  86203. }
  86204. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  86205. return null;
  86206. }
  86207. var impostorObjectCenter = impostor.getObjectCenter();
  86208. 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)
  86209. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  86210. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  86211. var hit = ray.intersectsMesh(impostor.object);
  86212. var contactPoint = hit.pickedPoint;
  86213. if (!contactPoint) {
  86214. return null;
  86215. }
  86216. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  86217. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  86218. var directionToOrigin = contactPoint.normalize();
  86219. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86220. directionToOrigin = directionToOrigin.negate();
  86221. }
  86222. // TODO: find a more physically based solution
  86223. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  86224. var forceX = directionToOrigin.x * this._strength / 8;
  86225. var forceY = directionToOrigin.y * this._updraftMultiplier;
  86226. var forceZ = directionToOrigin.z * this._strength / 8;
  86227. }
  86228. else {
  86229. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  86230. var forceY = this._originTop.y * this._updraftMultiplier;
  86231. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  86232. }
  86233. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  86234. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  86235. return { force: force, contactPoint: impostorObjectCenter };
  86236. };
  86237. PhysicsVortexEvent.prototype._tick = function () {
  86238. var _this = this;
  86239. this._physicsEngine.getImpostors().forEach(function (impostor) {
  86240. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  86241. if (!impostorForceAndContactPoint) {
  86242. return;
  86243. }
  86244. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  86245. });
  86246. };
  86247. /*** Helpers ***/
  86248. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86249. if (!this._cylinder) {
  86250. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86251. height: this._height,
  86252. diameter: this._radius * 2,
  86253. }, this._scene);
  86254. this._cylinder.isVisible = false;
  86255. }
  86256. };
  86257. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86258. var impostorObject = impostor.object;
  86259. this._prepareCylinder();
  86260. this._cylinder.position = this._cylinderPosition;
  86261. return this._cylinder.intersectsMesh(impostorObject, true);
  86262. };
  86263. return PhysicsVortexEvent;
  86264. }());
  86265. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86266. /***** Enums *****/
  86267. /**
  86268. * The strenght of the force in correspondence to the distance of the affected object
  86269. */
  86270. var PhysicsRadialImpulseFalloff;
  86271. (function (PhysicsRadialImpulseFalloff) {
  86272. /** Defines that impulse is constant in strength across it's whole radius */
  86273. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86274. /** DEfines that impulse gets weaker if it's further from the origin */
  86275. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86276. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86277. /**
  86278. * The strenght of the force in correspondence to the distance of the affected object
  86279. */
  86280. var PhysicsUpdraftMode;
  86281. (function (PhysicsUpdraftMode) {
  86282. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86283. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86284. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86285. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86286. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86287. })(BABYLON || (BABYLON = {}));
  86288. //# sourceMappingURL=babylon.physicsHelper.js.map
  86289. var BABYLON;
  86290. (function (BABYLON) {
  86291. var CannonJSPlugin = /** @class */ (function () {
  86292. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86293. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86294. if (iterations === void 0) { iterations = 10; }
  86295. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86296. this.name = "CannonJSPlugin";
  86297. this._physicsMaterials = new Array();
  86298. this._fixedTimeStep = 1 / 60;
  86299. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86300. this.BJSCANNON = CANNON;
  86301. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86302. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86303. this._tmpPosition = BABYLON.Vector3.Zero();
  86304. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86305. this._tmpUnityRotation = new BABYLON.Quaternion();
  86306. if (!this.isSupported()) {
  86307. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86308. return;
  86309. }
  86310. this._extendNamespace();
  86311. this.world = new this.BJSCANNON.World();
  86312. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86313. this.world.solver.iterations = iterations;
  86314. }
  86315. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86316. this.world.gravity.copy(gravity);
  86317. };
  86318. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86319. this._fixedTimeStep = timeStep;
  86320. };
  86321. CannonJSPlugin.prototype.getTimeStep = function () {
  86322. return this._fixedTimeStep;
  86323. };
  86324. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86325. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86326. };
  86327. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86328. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86329. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86330. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86331. };
  86332. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86333. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86334. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86335. impostor.physicsBody.applyForce(impulse, worldPoint);
  86336. };
  86337. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86338. //parent-child relationship. Does this impostor has a parent impostor?
  86339. if (impostor.parent) {
  86340. if (impostor.physicsBody) {
  86341. this.removePhysicsBody(impostor);
  86342. //TODO is that needed?
  86343. impostor.forceUpdate();
  86344. }
  86345. return;
  86346. }
  86347. //should a new body be created for this impostor?
  86348. if (impostor.isBodyInitRequired()) {
  86349. var shape = this._createShape(impostor);
  86350. //unregister events, if body is being changed
  86351. var oldBody = impostor.physicsBody;
  86352. if (oldBody) {
  86353. this.removePhysicsBody(impostor);
  86354. }
  86355. //create the body and material
  86356. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86357. var bodyCreationObject = {
  86358. mass: impostor.getParam("mass"),
  86359. material: material
  86360. };
  86361. // A simple extend, in case native options were used.
  86362. var nativeOptions = impostor.getParam("nativeOptions");
  86363. for (var key in nativeOptions) {
  86364. if (nativeOptions.hasOwnProperty(key)) {
  86365. bodyCreationObject[key] = nativeOptions[key];
  86366. }
  86367. }
  86368. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86369. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86370. this.world.addEventListener("preStep", impostor.beforeStep);
  86371. this.world.addEventListener("postStep", impostor.afterStep);
  86372. impostor.physicsBody.addShape(shape);
  86373. this.world.add(impostor.physicsBody);
  86374. //try to keep the body moving in the right direction by taking old properties.
  86375. //Should be tested!
  86376. if (oldBody) {
  86377. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86378. impostor.physicsBody[param].copy(oldBody[param]);
  86379. });
  86380. }
  86381. this._processChildMeshes(impostor);
  86382. }
  86383. //now update the body's transformation
  86384. this._updatePhysicsBodyTransformation(impostor);
  86385. };
  86386. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86387. var _this = this;
  86388. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86389. var currentRotation = mainImpostor.object.rotationQuaternion;
  86390. if (meshChildren.length) {
  86391. var processMesh = function (localPosition, mesh) {
  86392. if (!currentRotation || !mesh.rotationQuaternion) {
  86393. return;
  86394. }
  86395. var childImpostor = mesh.getPhysicsImpostor();
  86396. if (childImpostor) {
  86397. var parent = childImpostor.parent;
  86398. if (parent !== mainImpostor) {
  86399. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86400. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86401. if (childImpostor.physicsBody) {
  86402. _this.removePhysicsBody(childImpostor);
  86403. childImpostor.physicsBody = null;
  86404. }
  86405. childImpostor.parent = mainImpostor;
  86406. childImpostor.resetUpdateFlags();
  86407. 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));
  86408. //Add the mass of the children.
  86409. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86410. }
  86411. }
  86412. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86413. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86414. };
  86415. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86416. }
  86417. };
  86418. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86419. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86420. this.world.removeEventListener("preStep", impostor.beforeStep);
  86421. this.world.removeEventListener("postStep", impostor.afterStep);
  86422. this.world.remove(impostor.physicsBody);
  86423. };
  86424. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86425. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86426. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86427. if (!mainBody || !connectedBody) {
  86428. return;
  86429. }
  86430. var constraint;
  86431. var jointData = impostorJoint.joint.jointData;
  86432. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86433. var constraintData = {
  86434. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86435. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86436. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86437. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86438. maxForce: jointData.nativeParams.maxForce,
  86439. collideConnected: !!jointData.collision
  86440. };
  86441. switch (impostorJoint.joint.type) {
  86442. case BABYLON.PhysicsJoint.HingeJoint:
  86443. case BABYLON.PhysicsJoint.Hinge2Joint:
  86444. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86445. break;
  86446. case BABYLON.PhysicsJoint.DistanceJoint:
  86447. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86448. break;
  86449. case BABYLON.PhysicsJoint.SpringJoint:
  86450. var springData = jointData;
  86451. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86452. restLength: springData.length,
  86453. stiffness: springData.stiffness,
  86454. damping: springData.damping,
  86455. localAnchorA: constraintData.pivotA,
  86456. localAnchorB: constraintData.pivotB
  86457. });
  86458. break;
  86459. case BABYLON.PhysicsJoint.LockJoint:
  86460. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86461. break;
  86462. case BABYLON.PhysicsJoint.PointToPointJoint:
  86463. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86464. default:
  86465. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86466. break;
  86467. }
  86468. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86469. constraint.collideConnected = !!jointData.collision;
  86470. impostorJoint.joint.physicsJoint = constraint;
  86471. //don't add spring as constraint, as it is not one.
  86472. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86473. this.world.addConstraint(constraint);
  86474. }
  86475. else {
  86476. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86477. constraint.applyForce();
  86478. });
  86479. }
  86480. };
  86481. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86482. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86483. };
  86484. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86485. var index;
  86486. var mat;
  86487. for (index = 0; index < this._physicsMaterials.length; index++) {
  86488. mat = this._physicsMaterials[index];
  86489. if (mat.friction === friction && mat.restitution === restitution) {
  86490. return mat;
  86491. }
  86492. }
  86493. var currentMat = new this.BJSCANNON.Material(name);
  86494. currentMat.friction = friction;
  86495. currentMat.restitution = restitution;
  86496. this._physicsMaterials.push(currentMat);
  86497. return currentMat;
  86498. };
  86499. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86500. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86501. };
  86502. CannonJSPlugin.prototype._createShape = function (impostor) {
  86503. var object = impostor.object;
  86504. var returnValue;
  86505. var extendSize = impostor.getObjectExtendSize();
  86506. switch (impostor.type) {
  86507. case BABYLON.PhysicsImpostor.SphereImpostor:
  86508. var radiusX = extendSize.x;
  86509. var radiusY = extendSize.y;
  86510. var radiusZ = extendSize.z;
  86511. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86512. break;
  86513. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86514. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86515. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86516. break;
  86517. case BABYLON.PhysicsImpostor.BoxImpostor:
  86518. var box = extendSize.scale(0.5);
  86519. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86520. break;
  86521. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86522. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86523. returnValue = new this.BJSCANNON.Plane();
  86524. break;
  86525. case BABYLON.PhysicsImpostor.MeshImpostor:
  86526. // should transform the vertex data to world coordinates!!
  86527. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86528. var rawFaces = object.getIndices ? object.getIndices() : [];
  86529. if (!rawVerts)
  86530. return;
  86531. // get only scale! so the object could transform correctly.
  86532. var oldPosition = object.position.clone();
  86533. var oldRotation = object.rotation && object.rotation.clone();
  86534. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86535. object.position.copyFromFloats(0, 0, 0);
  86536. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86537. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86538. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86539. var transform = object.computeWorldMatrix(true);
  86540. // convert rawVerts to object space
  86541. var temp = new Array();
  86542. var index;
  86543. for (index = 0; index < rawVerts.length; index += 3) {
  86544. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86545. }
  86546. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86547. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86548. //now set back the transformation!
  86549. object.position.copyFrom(oldPosition);
  86550. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86551. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86552. break;
  86553. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86554. var oldPosition2 = object.position.clone();
  86555. var oldRotation2 = object.rotation && object.rotation.clone();
  86556. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86557. object.position.copyFromFloats(0, 0, 0);
  86558. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86559. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86560. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86561. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86562. returnValue = this._createHeightmap(object);
  86563. object.position.copyFrom(oldPosition2);
  86564. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86565. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86566. object.computeWorldMatrix(true);
  86567. break;
  86568. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86569. returnValue = new this.BJSCANNON.Particle();
  86570. break;
  86571. }
  86572. return returnValue;
  86573. };
  86574. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86575. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86576. var transform = object.computeWorldMatrix(true);
  86577. // convert rawVerts to object space
  86578. var temp = new Array();
  86579. var index;
  86580. for (index = 0; index < pos.length; index += 3) {
  86581. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86582. }
  86583. pos = temp;
  86584. var matrix = new Array();
  86585. //For now pointDepth will not be used and will be automatically calculated.
  86586. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86587. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86588. var boundingInfo = object.getBoundingInfo();
  86589. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86590. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86591. var elementSize = dim * 2 / arraySize;
  86592. for (var i = 0; i < pos.length; i = i + 3) {
  86593. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86594. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86595. var y = -pos[i + 2] + minY;
  86596. if (!matrix[x]) {
  86597. matrix[x] = [];
  86598. }
  86599. if (!matrix[x][z]) {
  86600. matrix[x][z] = y;
  86601. }
  86602. matrix[x][z] = Math.max(y, matrix[x][z]);
  86603. }
  86604. for (var x = 0; x <= arraySize; ++x) {
  86605. if (!matrix[x]) {
  86606. var loc = 1;
  86607. while (!matrix[(x + loc) % arraySize]) {
  86608. loc++;
  86609. }
  86610. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86611. //console.log("missing x", x);
  86612. }
  86613. for (var z = 0; z <= arraySize; ++z) {
  86614. if (!matrix[x][z]) {
  86615. var loc = 1;
  86616. var newValue;
  86617. while (newValue === undefined) {
  86618. newValue = matrix[x][(z + loc++) % arraySize];
  86619. }
  86620. matrix[x][z] = newValue;
  86621. }
  86622. }
  86623. }
  86624. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86625. elementSize: elementSize
  86626. });
  86627. //For future reference, needed for body transformation
  86628. shape.minY = minY;
  86629. return shape;
  86630. };
  86631. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86632. var object = impostor.object;
  86633. //make sure it is updated...
  86634. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86635. // The delta between the mesh position and the mesh bounding box center
  86636. var bInfo = object.getBoundingInfo();
  86637. if (!bInfo)
  86638. return;
  86639. var center = impostor.getObjectCenter();
  86640. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86641. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86642. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86643. this._tmpPosition.copyFrom(center);
  86644. var quaternion = object.rotationQuaternion;
  86645. if (!quaternion) {
  86646. return;
  86647. }
  86648. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86649. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86650. //-90 DEG in X, precalculated
  86651. quaternion = quaternion.multiply(this._minus90X);
  86652. //Invert! (Precalculated, 90 deg in X)
  86653. //No need to clone. this will never change.
  86654. impostor.setDeltaRotation(this._plus90X);
  86655. }
  86656. //If it is a heightfield, if should be centered.
  86657. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86658. var mesh = object;
  86659. var boundingInfo = mesh.getBoundingInfo();
  86660. //calculate the correct body position:
  86661. var rotationQuaternion = mesh.rotationQuaternion;
  86662. mesh.rotationQuaternion = this._tmpUnityRotation;
  86663. mesh.computeWorldMatrix(true);
  86664. //get original center with no rotation
  86665. var c = center.clone();
  86666. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86667. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86668. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86669. mesh.setPreTransformMatrix(p);
  86670. mesh.computeWorldMatrix(true);
  86671. //calculate the translation
  86672. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86673. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86674. //add it inverted to the delta
  86675. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86676. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86677. //rotation is back
  86678. mesh.rotationQuaternion = rotationQuaternion;
  86679. mesh.setPreTransformMatrix(oldPivot);
  86680. mesh.computeWorldMatrix(true);
  86681. }
  86682. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86683. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86684. //this._tmpPosition.copyFrom(object.position);
  86685. }
  86686. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86687. //Now update the impostor object
  86688. impostor.physicsBody.position.copy(this._tmpPosition);
  86689. impostor.physicsBody.quaternion.copy(quaternion);
  86690. };
  86691. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86692. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86693. if (impostor.object.rotationQuaternion) {
  86694. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86695. }
  86696. };
  86697. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86698. impostor.physicsBody.position.copy(newPosition);
  86699. impostor.physicsBody.quaternion.copy(newRotation);
  86700. };
  86701. CannonJSPlugin.prototype.isSupported = function () {
  86702. return this.BJSCANNON !== undefined;
  86703. };
  86704. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86705. impostor.physicsBody.velocity.copy(velocity);
  86706. };
  86707. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86708. impostor.physicsBody.angularVelocity.copy(velocity);
  86709. };
  86710. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86711. var v = impostor.physicsBody.velocity;
  86712. if (!v) {
  86713. return null;
  86714. }
  86715. return new BABYLON.Vector3(v.x, v.y, v.z);
  86716. };
  86717. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86718. var v = impostor.physicsBody.angularVelocity;
  86719. if (!v) {
  86720. return null;
  86721. }
  86722. return new BABYLON.Vector3(v.x, v.y, v.z);
  86723. };
  86724. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86725. impostor.physicsBody.mass = mass;
  86726. impostor.physicsBody.updateMassProperties();
  86727. };
  86728. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86729. return impostor.physicsBody.mass;
  86730. };
  86731. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86732. return impostor.physicsBody.material.friction;
  86733. };
  86734. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86735. impostor.physicsBody.material.friction = friction;
  86736. };
  86737. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86738. return impostor.physicsBody.material.restitution;
  86739. };
  86740. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86741. impostor.physicsBody.material.restitution = restitution;
  86742. };
  86743. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86744. impostor.physicsBody.sleep();
  86745. };
  86746. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86747. impostor.physicsBody.wakeUp();
  86748. };
  86749. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86750. joint.physicsJoint.distance = maxDistance;
  86751. };
  86752. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86753. // if (!motorIndex) {
  86754. // joint.physicsJoint.enableMotor();
  86755. // }
  86756. // }
  86757. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86758. // if (!motorIndex) {
  86759. // joint.physicsJoint.disableMotor();
  86760. // }
  86761. // }
  86762. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86763. if (!motorIndex) {
  86764. joint.physicsJoint.enableMotor();
  86765. joint.physicsJoint.setMotorSpeed(speed);
  86766. if (maxForce) {
  86767. this.setLimit(joint, maxForce);
  86768. }
  86769. }
  86770. };
  86771. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86772. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86773. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86774. };
  86775. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86776. var body = impostor.physicsBody;
  86777. mesh.position.x = body.position.x;
  86778. mesh.position.y = body.position.y;
  86779. mesh.position.z = body.position.z;
  86780. if (mesh.rotationQuaternion) {
  86781. mesh.rotationQuaternion.x = body.quaternion.x;
  86782. mesh.rotationQuaternion.y = body.quaternion.y;
  86783. mesh.rotationQuaternion.z = body.quaternion.z;
  86784. mesh.rotationQuaternion.w = body.quaternion.w;
  86785. }
  86786. };
  86787. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86788. var shape = impostor.physicsBody.shapes[0];
  86789. return shape.boundingSphereRadius;
  86790. };
  86791. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86792. var shape = impostor.physicsBody.shapes[0];
  86793. result.x = shape.halfExtents.x * 2;
  86794. result.y = shape.halfExtents.y * 2;
  86795. result.z = shape.halfExtents.z * 2;
  86796. };
  86797. CannonJSPlugin.prototype.dispose = function () {
  86798. };
  86799. CannonJSPlugin.prototype._extendNamespace = function () {
  86800. //this will force cannon to execute at least one step when using interpolation
  86801. var step_tmp1 = new this.BJSCANNON.Vec3();
  86802. var Engine = this.BJSCANNON;
  86803. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86804. maxSubSteps = maxSubSteps || 10;
  86805. timeSinceLastCalled = timeSinceLastCalled || 0;
  86806. if (timeSinceLastCalled === 0) {
  86807. this.internalStep(dt);
  86808. this.time += dt;
  86809. }
  86810. else {
  86811. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86812. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86813. var t0 = performance.now();
  86814. for (var i = 0; i !== internalSteps; i++) {
  86815. this.internalStep(dt);
  86816. if (performance.now() - t0 > dt * 1000) {
  86817. break;
  86818. }
  86819. }
  86820. this.time += timeSinceLastCalled;
  86821. var h = this.time % dt;
  86822. var h_div_dt = h / dt;
  86823. var interpvelo = step_tmp1;
  86824. var bodies = this.bodies;
  86825. for (var j = 0; j !== bodies.length; j++) {
  86826. var b = bodies[j];
  86827. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86828. b.position.vsub(b.previousPosition, interpvelo);
  86829. interpvelo.scale(h_div_dt, interpvelo);
  86830. b.position.vadd(interpvelo, b.interpolatedPosition);
  86831. }
  86832. else {
  86833. b.interpolatedPosition.copy(b.position);
  86834. b.interpolatedQuaternion.copy(b.quaternion);
  86835. }
  86836. }
  86837. }
  86838. };
  86839. };
  86840. return CannonJSPlugin;
  86841. }());
  86842. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86843. })(BABYLON || (BABYLON = {}));
  86844. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86845. var BABYLON;
  86846. (function (BABYLON) {
  86847. var OimoJSPlugin = /** @class */ (function () {
  86848. function OimoJSPlugin(iterations) {
  86849. this.name = "OimoJSPlugin";
  86850. this._tmpImpostorsArray = [];
  86851. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86852. this.BJSOIMO = OIMO;
  86853. this.world = new this.BJSOIMO.World({
  86854. iterations: iterations
  86855. });
  86856. this.world.clear();
  86857. }
  86858. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86859. this.world.gravity.copy(gravity);
  86860. };
  86861. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86862. this.world.timeStep = timeStep;
  86863. };
  86864. OimoJSPlugin.prototype.getTimeStep = function () {
  86865. return this.world.timeStep;
  86866. };
  86867. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86868. var _this = this;
  86869. impostors.forEach(function (impostor) {
  86870. impostor.beforeStep();
  86871. });
  86872. this.world.step();
  86873. impostors.forEach(function (impostor) {
  86874. impostor.afterStep();
  86875. //update the ordered impostors array
  86876. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86877. });
  86878. //check for collisions
  86879. var contact = this.world.contacts;
  86880. while (contact !== null) {
  86881. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86882. contact = contact.next;
  86883. continue;
  86884. }
  86885. //is this body colliding with any other? get the impostor
  86886. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86887. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86888. if (!mainImpostor || !collidingImpostor) {
  86889. contact = contact.next;
  86890. continue;
  86891. }
  86892. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86893. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86894. contact = contact.next;
  86895. }
  86896. };
  86897. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86898. var mass = impostor.physicsBody.mass;
  86899. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86900. };
  86901. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86902. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86903. this.applyImpulse(impostor, force, contactPoint);
  86904. };
  86905. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86906. var _this = this;
  86907. //parent-child relationship. Does this impostor has a parent impostor?
  86908. if (impostor.parent) {
  86909. if (impostor.physicsBody) {
  86910. this.removePhysicsBody(impostor);
  86911. //TODO is that needed?
  86912. impostor.forceUpdate();
  86913. }
  86914. return;
  86915. }
  86916. if (impostor.isBodyInitRequired()) {
  86917. var bodyConfig = {
  86918. name: impostor.uniqueId,
  86919. //Oimo must have mass, also for static objects.
  86920. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86921. size: [],
  86922. type: [],
  86923. pos: [],
  86924. posShape: [],
  86925. rot: [],
  86926. rotShape: [],
  86927. move: impostor.getParam("mass") !== 0,
  86928. density: impostor.getParam("mass"),
  86929. friction: impostor.getParam("friction"),
  86930. restitution: impostor.getParam("restitution"),
  86931. //Supporting older versions of Oimo
  86932. world: this.world
  86933. };
  86934. var impostors = [impostor];
  86935. var addToArray = function (parent) {
  86936. if (!parent.getChildMeshes)
  86937. return;
  86938. parent.getChildMeshes().forEach(function (m) {
  86939. if (m.physicsImpostor) {
  86940. impostors.push(m.physicsImpostor);
  86941. //m.physicsImpostor._init();
  86942. }
  86943. });
  86944. };
  86945. addToArray(impostor.object);
  86946. var checkWithEpsilon_1 = function (value) {
  86947. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86948. };
  86949. var globalQuaternion_1 = new BABYLON.Quaternion();
  86950. impostors.forEach(function (i) {
  86951. if (!i.object.rotationQuaternion) {
  86952. return;
  86953. }
  86954. //get the correct bounding box
  86955. var oldQuaternion = i.object.rotationQuaternion;
  86956. globalQuaternion_1 = oldQuaternion.clone();
  86957. var rot = oldQuaternion.toEulerAngles();
  86958. var extendSize = i.getObjectExtendSize();
  86959. var radToDeg = 57.295779513082320876;
  86960. if (i === impostor) {
  86961. var center = impostor.getObjectCenter();
  86962. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86963. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86964. //Can also use Array.prototype.push.apply
  86965. bodyConfig.pos.push(center.x);
  86966. bodyConfig.pos.push(center.y);
  86967. bodyConfig.pos.push(center.z);
  86968. bodyConfig.posShape.push(0, 0, 0);
  86969. //tmp solution
  86970. bodyConfig.rot.push(0);
  86971. bodyConfig.rot.push(0);
  86972. bodyConfig.rot.push(0);
  86973. bodyConfig.rotShape.push(0, 0, 0);
  86974. }
  86975. else {
  86976. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86977. bodyConfig.posShape.push(localPosition.x);
  86978. bodyConfig.posShape.push(localPosition.y);
  86979. bodyConfig.posShape.push(localPosition.z);
  86980. bodyConfig.pos.push(0, 0, 0);
  86981. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86982. bodyConfig.rot.push(0);
  86983. bodyConfig.rot.push(0);
  86984. bodyConfig.rot.push(0);
  86985. bodyConfig.rotShape.push(rot.x * radToDeg);
  86986. bodyConfig.rotShape.push(rot.y * radToDeg);
  86987. bodyConfig.rotShape.push(rot.z * radToDeg);
  86988. }
  86989. // register mesh
  86990. switch (i.type) {
  86991. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86992. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86993. case BABYLON.PhysicsImpostor.SphereImpostor:
  86994. var radiusX = extendSize.x;
  86995. var radiusY = extendSize.y;
  86996. var radiusZ = extendSize.z;
  86997. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86998. bodyConfig.type.push('sphere');
  86999. //due to the way oimo works with compounds, add 3 times
  87000. bodyConfig.size.push(size);
  87001. bodyConfig.size.push(size);
  87002. bodyConfig.size.push(size);
  87003. break;
  87004. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87005. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  87006. var sizeY = checkWithEpsilon_1(extendSize.y);
  87007. bodyConfig.type.push('cylinder');
  87008. bodyConfig.size.push(sizeX);
  87009. bodyConfig.size.push(sizeY);
  87010. //due to the way oimo works with compounds, add one more value.
  87011. bodyConfig.size.push(sizeY);
  87012. break;
  87013. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87014. case BABYLON.PhysicsImpostor.BoxImpostor:
  87015. default:
  87016. var sizeX = checkWithEpsilon_1(extendSize.x);
  87017. var sizeY = checkWithEpsilon_1(extendSize.y);
  87018. var sizeZ = checkWithEpsilon_1(extendSize.z);
  87019. bodyConfig.type.push('box');
  87020. //if (i === impostor) {
  87021. bodyConfig.size.push(sizeX);
  87022. bodyConfig.size.push(sizeY);
  87023. bodyConfig.size.push(sizeZ);
  87024. //} else {
  87025. // bodyConfig.size.push(0,0,0);
  87026. //}
  87027. break;
  87028. }
  87029. //actually not needed, but hey...
  87030. i.object.rotationQuaternion = oldQuaternion;
  87031. });
  87032. impostor.physicsBody = this.world.add(bodyConfig);
  87033. // set the quaternion, ignoring the previously defined (euler) rotation
  87034. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  87035. // update with delta 0, so the body will reveive the new rotation.
  87036. impostor.physicsBody.updatePosition(0);
  87037. }
  87038. else {
  87039. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  87040. }
  87041. impostor.setDeltaPosition(this._tmpPositionVector);
  87042. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  87043. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  87044. };
  87045. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87046. //impostor.physicsBody.dispose();
  87047. //Same as : (older oimo versions)
  87048. this.world.removeRigidBody(impostor.physicsBody);
  87049. };
  87050. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87051. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87052. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87053. if (!mainBody || !connectedBody) {
  87054. return;
  87055. }
  87056. var jointData = impostorJoint.joint.jointData;
  87057. var options = jointData.nativeParams || {};
  87058. var type;
  87059. var nativeJointData = {
  87060. body1: mainBody,
  87061. body2: connectedBody,
  87062. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  87063. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  87064. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  87065. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  87066. min: options.min,
  87067. max: options.max,
  87068. collision: options.collision || jointData.collision,
  87069. spring: options.spring,
  87070. //supporting older version of Oimo
  87071. world: this.world
  87072. };
  87073. switch (impostorJoint.joint.type) {
  87074. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87075. type = "jointBall";
  87076. break;
  87077. case BABYLON.PhysicsJoint.SpringJoint:
  87078. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  87079. var springData = jointData;
  87080. nativeJointData.min = springData.length || nativeJointData.min;
  87081. //Max should also be set, just make sure it is at least min
  87082. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  87083. case BABYLON.PhysicsJoint.DistanceJoint:
  87084. type = "jointDistance";
  87085. nativeJointData.max = jointData.maxDistance;
  87086. break;
  87087. case BABYLON.PhysicsJoint.PrismaticJoint:
  87088. type = "jointPrisme";
  87089. break;
  87090. case BABYLON.PhysicsJoint.SliderJoint:
  87091. type = "jointSlide";
  87092. break;
  87093. case BABYLON.PhysicsJoint.WheelJoint:
  87094. type = "jointWheel";
  87095. break;
  87096. case BABYLON.PhysicsJoint.HingeJoint:
  87097. default:
  87098. type = "jointHinge";
  87099. break;
  87100. }
  87101. nativeJointData.type = type;
  87102. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  87103. };
  87104. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87105. //Bug in Oimo prevents us from disposing a joint in the playground
  87106. //joint.joint.physicsJoint.dispose();
  87107. //So we will bruteforce it!
  87108. try {
  87109. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  87110. }
  87111. catch (e) {
  87112. BABYLON.Tools.Warn(e);
  87113. }
  87114. };
  87115. OimoJSPlugin.prototype.isSupported = function () {
  87116. return this.BJSOIMO !== undefined;
  87117. };
  87118. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  87119. if (!impostor.physicsBody.sleeping) {
  87120. //TODO check that
  87121. /*if (impostor.physicsBody.shapes.next) {
  87122. var parentShape = this._getLastShape(impostor.physicsBody);
  87123. impostor.object.position.copyFrom(parentShape.position);
  87124. console.log(parentShape.position);
  87125. } else {*/
  87126. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  87127. //}
  87128. if (impostor.object.rotationQuaternion) {
  87129. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  87130. }
  87131. }
  87132. };
  87133. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  87134. var body = impostor.physicsBody;
  87135. body.position.copy(newPosition);
  87136. body.orientation.copy(newRotation);
  87137. body.syncShapes();
  87138. body.awake();
  87139. };
  87140. /*private _getLastShape(body: any): any {
  87141. var lastShape = body.shapes;
  87142. while (lastShape.next) {
  87143. lastShape = lastShape.next;
  87144. }
  87145. return lastShape;
  87146. }*/
  87147. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  87148. impostor.physicsBody.linearVelocity.copy(velocity);
  87149. };
  87150. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  87151. impostor.physicsBody.angularVelocity.copy(velocity);
  87152. };
  87153. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  87154. var v = impostor.physicsBody.linearVelocity;
  87155. if (!v) {
  87156. return null;
  87157. }
  87158. return new BABYLON.Vector3(v.x, v.y, v.z);
  87159. };
  87160. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  87161. var v = impostor.physicsBody.angularVelocity;
  87162. if (!v) {
  87163. return null;
  87164. }
  87165. return new BABYLON.Vector3(v.x, v.y, v.z);
  87166. };
  87167. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  87168. var staticBody = mass === 0;
  87169. //this will actually set the body's density and not its mass.
  87170. //But this is how oimo treats the mass variable.
  87171. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  87172. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  87173. };
  87174. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  87175. return impostor.physicsBody.shapes.density;
  87176. };
  87177. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  87178. return impostor.physicsBody.shapes.friction;
  87179. };
  87180. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  87181. impostor.physicsBody.shapes.friction = friction;
  87182. };
  87183. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  87184. return impostor.physicsBody.shapes.restitution;
  87185. };
  87186. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  87187. impostor.physicsBody.shapes.restitution = restitution;
  87188. };
  87189. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  87190. impostor.physicsBody.sleep();
  87191. };
  87192. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  87193. impostor.physicsBody.awake();
  87194. };
  87195. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  87196. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  87197. if (minDistance !== void 0) {
  87198. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  87199. }
  87200. };
  87201. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  87202. //TODO separate rotational and transational motors.
  87203. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87204. if (motor) {
  87205. motor.setMotor(speed, maxForce);
  87206. }
  87207. };
  87208. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  87209. //TODO separate rotational and transational motors.
  87210. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  87211. if (motor) {
  87212. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  87213. }
  87214. };
  87215. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  87216. var body = impostor.physicsBody;
  87217. mesh.position.x = body.position.x;
  87218. mesh.position.y = body.position.y;
  87219. mesh.position.z = body.position.z;
  87220. if (mesh.rotationQuaternion) {
  87221. mesh.rotationQuaternion.x = body.orientation.x;
  87222. mesh.rotationQuaternion.y = body.orientation.y;
  87223. mesh.rotationQuaternion.z = body.orientation.z;
  87224. mesh.rotationQuaternion.w = body.orientation.s;
  87225. }
  87226. };
  87227. OimoJSPlugin.prototype.getRadius = function (impostor) {
  87228. return impostor.physicsBody.shapes.radius;
  87229. };
  87230. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  87231. var shape = impostor.physicsBody.shapes;
  87232. result.x = shape.halfWidth * 2;
  87233. result.y = shape.halfHeight * 2;
  87234. result.z = shape.halfDepth * 2;
  87235. };
  87236. OimoJSPlugin.prototype.dispose = function () {
  87237. this.world.clear();
  87238. };
  87239. return OimoJSPlugin;
  87240. }());
  87241. BABYLON.OimoJSPlugin = OimoJSPlugin;
  87242. })(BABYLON || (BABYLON = {}));
  87243. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  87244. var BABYLON;
  87245. (function (BABYLON) {
  87246. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87247. // All values and structures referenced from:
  87248. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87249. var DDS_MAGIC = 0x20534444;
  87250. var
  87251. //DDSD_CAPS = 0x1,
  87252. //DDSD_HEIGHT = 0x2,
  87253. //DDSD_WIDTH = 0x4,
  87254. //DDSD_PITCH = 0x8,
  87255. //DDSD_PIXELFORMAT = 0x1000,
  87256. DDSD_MIPMAPCOUNT = 0x20000;
  87257. //DDSD_LINEARSIZE = 0x80000,
  87258. //DDSD_DEPTH = 0x800000;
  87259. // var DDSCAPS_COMPLEX = 0x8,
  87260. // DDSCAPS_MIPMAP = 0x400000,
  87261. // DDSCAPS_TEXTURE = 0x1000;
  87262. var DDSCAPS2_CUBEMAP = 0x200;
  87263. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87264. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87265. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87266. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87267. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87268. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87269. // DDSCAPS2_VOLUME = 0x200000;
  87270. var
  87271. //DDPF_ALPHAPIXELS = 0x1,
  87272. //DDPF_ALPHA = 0x2,
  87273. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87274. //DDPF_YUV = 0x200,
  87275. DDPF_LUMINANCE = 0x20000;
  87276. function FourCCToInt32(value) {
  87277. return value.charCodeAt(0) +
  87278. (value.charCodeAt(1) << 8) +
  87279. (value.charCodeAt(2) << 16) +
  87280. (value.charCodeAt(3) << 24);
  87281. }
  87282. function Int32ToFourCC(value) {
  87283. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87284. }
  87285. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87286. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87287. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87288. var FOURCC_DX10 = FourCCToInt32("DX10");
  87289. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87290. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87291. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87292. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87293. var headerLengthInt = 31; // The header length in 32 bit ints
  87294. // Offsets into the header array
  87295. var off_magic = 0;
  87296. var off_size = 1;
  87297. var off_flags = 2;
  87298. var off_height = 3;
  87299. var off_width = 4;
  87300. var off_mipmapCount = 7;
  87301. var off_pfFlags = 20;
  87302. var off_pfFourCC = 21;
  87303. var off_RGBbpp = 22;
  87304. var off_RMask = 23;
  87305. var off_GMask = 24;
  87306. var off_BMask = 25;
  87307. var off_AMask = 26;
  87308. // var off_caps1 = 27;
  87309. var off_caps2 = 28;
  87310. // var off_caps3 = 29;
  87311. // var off_caps4 = 30;
  87312. var off_dxgiFormat = 32;
  87313. ;
  87314. var DDSTools = /** @class */ (function () {
  87315. function DDSTools() {
  87316. }
  87317. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87318. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87319. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87320. var mipmapCount = 1;
  87321. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87322. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87323. }
  87324. var fourCC = header[off_pfFourCC];
  87325. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87326. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87327. switch (fourCC) {
  87328. case FOURCC_D3DFMT_R16G16B16A16F:
  87329. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87330. break;
  87331. case FOURCC_D3DFMT_R32G32B32A32F:
  87332. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87333. break;
  87334. case FOURCC_DX10:
  87335. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87336. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87337. break;
  87338. }
  87339. }
  87340. return {
  87341. width: header[off_width],
  87342. height: header[off_height],
  87343. mipmapCount: mipmapCount,
  87344. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87345. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87346. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87347. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87348. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87349. dxgiFormat: dxgiFormat,
  87350. textureType: textureType
  87351. };
  87352. };
  87353. DDSTools._ToHalfFloat = function (value) {
  87354. if (!DDSTools._FloatView) {
  87355. DDSTools._FloatView = new Float32Array(1);
  87356. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87357. }
  87358. DDSTools._FloatView[0] = value;
  87359. var x = DDSTools._Int32View[0];
  87360. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87361. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87362. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87363. /* If zero, or denormal, or exponent underflows too much for a denormal
  87364. * half, return signed zero. */
  87365. if (e < 103) {
  87366. return bits;
  87367. }
  87368. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87369. if (e > 142) {
  87370. bits |= 0x7c00;
  87371. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87372. * not Inf, so make sure we set one mantissa bit too. */
  87373. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87374. return bits;
  87375. }
  87376. /* If exponent underflows but not too much, return a denormal */
  87377. if (e < 113) {
  87378. m |= 0x0800;
  87379. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87380. * to 1, which is OK. */
  87381. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87382. return bits;
  87383. }
  87384. bits |= ((e - 112) << 10) | (m >> 1);
  87385. bits += m & 1;
  87386. return bits;
  87387. };
  87388. DDSTools._FromHalfFloat = function (value) {
  87389. var s = (value & 0x8000) >> 15;
  87390. var e = (value & 0x7C00) >> 10;
  87391. var f = value & 0x03FF;
  87392. if (e === 0) {
  87393. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87394. }
  87395. else if (e == 0x1F) {
  87396. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87397. }
  87398. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87399. };
  87400. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87401. var destArray = new Float32Array(dataLength);
  87402. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87403. var index = 0;
  87404. for (var y = 0; y < height; y++) {
  87405. for (var x = 0; x < width; x++) {
  87406. var srcPos = (x + y * width) * 4;
  87407. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87408. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87409. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87410. if (DDSTools.StoreLODInAlphaChannel) {
  87411. destArray[index + 3] = lod;
  87412. }
  87413. else {
  87414. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87415. }
  87416. index += 4;
  87417. }
  87418. }
  87419. return destArray;
  87420. };
  87421. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87422. if (DDSTools.StoreLODInAlphaChannel) {
  87423. var destArray = new Uint16Array(dataLength);
  87424. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87425. var index = 0;
  87426. for (var y = 0; y < height; y++) {
  87427. for (var x = 0; x < width; x++) {
  87428. var srcPos = (x + y * width) * 4;
  87429. destArray[index] = srcData[srcPos];
  87430. destArray[index + 1] = srcData[srcPos + 1];
  87431. destArray[index + 2] = srcData[srcPos + 2];
  87432. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87433. index += 4;
  87434. }
  87435. }
  87436. return destArray;
  87437. }
  87438. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87439. };
  87440. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87441. if (DDSTools.StoreLODInAlphaChannel) {
  87442. var destArray = new Float32Array(dataLength);
  87443. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87444. var index = 0;
  87445. for (var y = 0; y < height; y++) {
  87446. for (var x = 0; x < width; x++) {
  87447. var srcPos = (x + y * width) * 4;
  87448. destArray[index] = srcData[srcPos];
  87449. destArray[index + 1] = srcData[srcPos + 1];
  87450. destArray[index + 2] = srcData[srcPos + 2];
  87451. destArray[index + 3] = lod;
  87452. index += 4;
  87453. }
  87454. }
  87455. return destArray;
  87456. }
  87457. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87458. };
  87459. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87460. var destArray = new Uint8Array(dataLength);
  87461. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87462. var index = 0;
  87463. for (var y = 0; y < height; y++) {
  87464. for (var x = 0; x < width; x++) {
  87465. var srcPos = (x + y * width) * 4;
  87466. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87467. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87468. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87469. if (DDSTools.StoreLODInAlphaChannel) {
  87470. destArray[index + 3] = lod;
  87471. }
  87472. else {
  87473. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87474. }
  87475. index += 4;
  87476. }
  87477. }
  87478. return destArray;
  87479. };
  87480. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87481. var destArray = new Uint8Array(dataLength);
  87482. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87483. var index = 0;
  87484. for (var y = 0; y < height; y++) {
  87485. for (var x = 0; x < width; x++) {
  87486. var srcPos = (x + y * width) * 4;
  87487. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87488. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87489. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87490. if (DDSTools.StoreLODInAlphaChannel) {
  87491. destArray[index + 3] = lod;
  87492. }
  87493. else {
  87494. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87495. }
  87496. index += 4;
  87497. }
  87498. }
  87499. return destArray;
  87500. };
  87501. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87502. var byteArray = new Uint8Array(dataLength);
  87503. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87504. var index = 0;
  87505. for (var y = 0; y < height; y++) {
  87506. for (var x = 0; x < width; x++) {
  87507. var srcPos = (x + y * width) * 4;
  87508. byteArray[index] = srcData[srcPos + rOffset];
  87509. byteArray[index + 1] = srcData[srcPos + gOffset];
  87510. byteArray[index + 2] = srcData[srcPos + bOffset];
  87511. byteArray[index + 3] = srcData[srcPos + aOffset];
  87512. index += 4;
  87513. }
  87514. }
  87515. return byteArray;
  87516. };
  87517. DDSTools._ExtractLongWordOrder = function (value) {
  87518. if (value === 0 || value === 255 || value === -16777216) {
  87519. return 0;
  87520. }
  87521. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87522. };
  87523. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87524. var byteArray = new Uint8Array(dataLength);
  87525. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87526. var index = 0;
  87527. for (var y = 0; y < height; y++) {
  87528. for (var x = 0; x < width; x++) {
  87529. var srcPos = (x + y * width) * 3;
  87530. byteArray[index] = srcData[srcPos + rOffset];
  87531. byteArray[index + 1] = srcData[srcPos + gOffset];
  87532. byteArray[index + 2] = srcData[srcPos + bOffset];
  87533. index += 3;
  87534. }
  87535. }
  87536. return byteArray;
  87537. };
  87538. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87539. var byteArray = new Uint8Array(dataLength);
  87540. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87541. var index = 0;
  87542. for (var y = 0; y < height; y++) {
  87543. for (var x = 0; x < width; x++) {
  87544. var srcPos = (x + y * width);
  87545. byteArray[index] = srcData[srcPos];
  87546. index++;
  87547. }
  87548. }
  87549. return byteArray;
  87550. };
  87551. /**
  87552. * Uploads DDS Levels to a Babylon Texture
  87553. * @hidden
  87554. */
  87555. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87556. if (lodIndex === void 0) { lodIndex = -1; }
  87557. var sphericalPolynomialFaces = null;
  87558. if (info.sphericalPolynomial) {
  87559. sphericalPolynomialFaces = new Array();
  87560. }
  87561. var ext = engine.getCaps().s3tc;
  87562. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87563. var fourCC, width, height, dataLength = 0, dataOffset;
  87564. var byteArray, mipmapCount, mip;
  87565. var internalCompressedFormat = 0;
  87566. var blockBytes = 1;
  87567. if (header[off_magic] !== DDS_MAGIC) {
  87568. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87569. return;
  87570. }
  87571. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87572. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87573. return;
  87574. }
  87575. if (info.isCompressed && !ext) {
  87576. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87577. return;
  87578. }
  87579. var bpp = header[off_RGBbpp];
  87580. dataOffset = header[off_size] + 4;
  87581. var computeFormats = false;
  87582. if (info.isFourCC) {
  87583. fourCC = header[off_pfFourCC];
  87584. switch (fourCC) {
  87585. case FOURCC_DXT1:
  87586. blockBytes = 8;
  87587. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87588. break;
  87589. case FOURCC_DXT3:
  87590. blockBytes = 16;
  87591. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87592. break;
  87593. case FOURCC_DXT5:
  87594. blockBytes = 16;
  87595. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87596. break;
  87597. case FOURCC_D3DFMT_R16G16B16A16F:
  87598. computeFormats = true;
  87599. break;
  87600. case FOURCC_D3DFMT_R32G32B32A32F:
  87601. computeFormats = true;
  87602. break;
  87603. case FOURCC_DX10:
  87604. // There is an additionnal header so dataOffset need to be changed
  87605. dataOffset += 5 * 4; // 5 uints
  87606. var supported = false;
  87607. switch (info.dxgiFormat) {
  87608. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87609. computeFormats = true;
  87610. supported = true;
  87611. break;
  87612. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87613. info.isRGB = true;
  87614. info.isFourCC = false;
  87615. bpp = 32;
  87616. supported = true;
  87617. break;
  87618. }
  87619. if (supported) {
  87620. break;
  87621. }
  87622. default:
  87623. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87624. return;
  87625. }
  87626. }
  87627. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87628. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87629. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87630. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87631. if (computeFormats) {
  87632. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87633. }
  87634. mipmapCount = 1;
  87635. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87636. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87637. }
  87638. for (var face = 0; face < faces; face++) {
  87639. width = header[off_width];
  87640. height = header[off_height];
  87641. for (mip = 0; mip < mipmapCount; ++mip) {
  87642. if (lodIndex === -1 || lodIndex === mip) {
  87643. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87644. var i = (lodIndex === -1) ? mip : 0;
  87645. if (!info.isCompressed && info.isFourCC) {
  87646. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87647. dataLength = width * height * 4;
  87648. var floatArray = null;
  87649. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87650. if (bpp === 128) {
  87651. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87652. if (sphericalPolynomialFaces && i == 0) {
  87653. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87654. }
  87655. }
  87656. else if (bpp === 64) {
  87657. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87658. if (sphericalPolynomialFaces && i == 0) {
  87659. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87660. }
  87661. }
  87662. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87663. }
  87664. else {
  87665. if (bpp === 128) {
  87666. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87667. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87668. if (sphericalPolynomialFaces && i == 0) {
  87669. sphericalPolynomialFaces.push(floatArray);
  87670. }
  87671. }
  87672. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87673. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87674. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87675. if (sphericalPolynomialFaces && i == 0) {
  87676. sphericalPolynomialFaces.push(floatArray);
  87677. }
  87678. }
  87679. else { // 64
  87680. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87681. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87682. if (sphericalPolynomialFaces && i == 0) {
  87683. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87684. }
  87685. }
  87686. }
  87687. if (floatArray) {
  87688. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  87689. }
  87690. }
  87691. else if (info.isRGB) {
  87692. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87693. if (bpp === 24) {
  87694. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  87695. dataLength = width * height * 3;
  87696. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87697. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87698. }
  87699. else { // 32
  87700. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  87701. dataLength = width * height * 4;
  87702. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87703. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87704. }
  87705. }
  87706. else if (info.isLuminance) {
  87707. var unpackAlignment = engine._getUnpackAlignement();
  87708. var unpaddedRowSize = width;
  87709. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87710. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87711. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87712. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  87713. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87714. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  87715. }
  87716. else {
  87717. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87718. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87719. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87720. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  87721. }
  87722. }
  87723. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87724. width *= 0.5;
  87725. height *= 0.5;
  87726. width = Math.max(1.0, width);
  87727. height = Math.max(1.0, height);
  87728. }
  87729. if (currentFace !== undefined) {
  87730. // Loading a single face
  87731. break;
  87732. }
  87733. }
  87734. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87735. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87736. size: header[off_width],
  87737. right: sphericalPolynomialFaces[0],
  87738. left: sphericalPolynomialFaces[1],
  87739. up: sphericalPolynomialFaces[2],
  87740. down: sphericalPolynomialFaces[3],
  87741. front: sphericalPolynomialFaces[4],
  87742. back: sphericalPolynomialFaces[5],
  87743. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87744. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87745. gammaSpace: false,
  87746. });
  87747. }
  87748. else {
  87749. info.sphericalPolynomial = undefined;
  87750. }
  87751. };
  87752. DDSTools.StoreLODInAlphaChannel = false;
  87753. return DDSTools;
  87754. }());
  87755. BABYLON.DDSTools = DDSTools;
  87756. })(BABYLON || (BABYLON = {}));
  87757. //# sourceMappingURL=babylon.dds.js.map
  87758. var BABYLON;
  87759. (function (BABYLON) {
  87760. /**
  87761. * Implementation of the DDS Texture Loader.
  87762. */
  87763. var DDSTextureLoader = /** @class */ (function () {
  87764. function DDSTextureLoader() {
  87765. /**
  87766. * Defines wether the loader supports cascade loading the different faces.
  87767. */
  87768. this.supportCascades = true;
  87769. }
  87770. /**
  87771. * This returns if the loader support the current file information.
  87772. * @param extension defines the file extension of the file being loaded
  87773. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87774. * @param fallback defines the fallback internal texture if any
  87775. * @param isBase64 defines whether the texture is encoded as a base64
  87776. * @param isBuffer defines whether the texture data are stored as a buffer
  87777. * @returns true if the loader can load the specified file
  87778. */
  87779. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  87780. return extension.indexOf(".dds") === 0;
  87781. };
  87782. /**
  87783. * Transform the url before loading if required.
  87784. * @param rootUrl the url of the texture
  87785. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87786. * @returns the transformed texture
  87787. */
  87788. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  87789. return rootUrl;
  87790. };
  87791. /**
  87792. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  87793. * @param rootUrl the url of the texture
  87794. * @param textureFormatInUse defines the current compressed format in use iun the engine
  87795. * @returns the fallback texture
  87796. */
  87797. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  87798. return null;
  87799. };
  87800. /**
  87801. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  87802. * @param data contains the texture data
  87803. * @param texture defines the BabylonJS internal texture
  87804. * @param createPolynomials will be true if polynomials have been requested
  87805. * @param onLoad defines the callback to trigger once the texture is ready
  87806. * @param onError defines the callback to trigger in case of error
  87807. */
  87808. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  87809. var engine = texture.getEngine();
  87810. var info;
  87811. var loadMipmap = false;
  87812. if (Array.isArray(imgs)) {
  87813. for (var index = 0; index < imgs.length; index++) {
  87814. var data_1 = imgs[index];
  87815. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  87816. texture.width = info.width;
  87817. texture.height = info.height;
  87818. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87819. engine._unpackFlipY(info.isCompressed);
  87820. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  87821. if (!info.isFourCC && info.mipmapCount === 1) {
  87822. engine.generateMipMapsForCubemap(texture);
  87823. }
  87824. }
  87825. }
  87826. else {
  87827. var data = imgs;
  87828. info = BABYLON.DDSTools.GetDDSInfo(data);
  87829. texture.width = info.width;
  87830. texture.height = info.height;
  87831. if (createPolynomials) {
  87832. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  87833. }
  87834. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  87835. engine._unpackFlipY(info.isCompressed);
  87836. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  87837. if (!info.isFourCC && info.mipmapCount === 1) {
  87838. engine.generateMipMapsForCubemap(texture);
  87839. }
  87840. }
  87841. engine._setCubeMapTextureParams(loadMipmap);
  87842. texture.isReady = true;
  87843. if (onLoad) {
  87844. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  87845. }
  87846. };
  87847. /**
  87848. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  87849. * @param data contains the texture data
  87850. * @param texture defines the BabylonJS internal texture
  87851. * @param callback defines the method to call once ready to upload
  87852. */
  87853. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  87854. var info = BABYLON.DDSTools.GetDDSInfo(data);
  87855. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  87856. callback(info.width, info.height, !loadMipmap, info.isFourCC, function () {
  87857. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  87858. });
  87859. };
  87860. return DDSTextureLoader;
  87861. }());
  87862. // Register the loader.
  87863. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  87864. })(BABYLON || (BABYLON = {}));
  87865. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  87866. var BABYLON;
  87867. (function (BABYLON) {
  87868. /*
  87869. * Based on jsTGALoader - Javascript loader for TGA file
  87870. * By Vincent Thibault
  87871. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  87872. */
  87873. var TGATools = /** @class */ (function () {
  87874. function TGATools() {
  87875. }
  87876. TGATools.GetTGAHeader = function (data) {
  87877. var offset = 0;
  87878. var header = {
  87879. id_length: data[offset++],
  87880. colormap_type: data[offset++],
  87881. image_type: data[offset++],
  87882. colormap_index: data[offset++] | data[offset++] << 8,
  87883. colormap_length: data[offset++] | data[offset++] << 8,
  87884. colormap_size: data[offset++],
  87885. origin: [
  87886. data[offset++] | data[offset++] << 8,
  87887. data[offset++] | data[offset++] << 8
  87888. ],
  87889. width: data[offset++] | data[offset++] << 8,
  87890. height: data[offset++] | data[offset++] << 8,
  87891. pixel_size: data[offset++],
  87892. flags: data[offset++]
  87893. };
  87894. return header;
  87895. };
  87896. /**
  87897. * Uploads TGA content to a Babylon Texture
  87898. * @hidden
  87899. */
  87900. TGATools.UploadContent = function (texture, data) {
  87901. // Not enough data to contain header ?
  87902. if (data.length < 19) {
  87903. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87904. return;
  87905. }
  87906. // Read Header
  87907. var offset = 18;
  87908. var header = TGATools.GetTGAHeader(data);
  87909. // Assume it's a valid Targa file.
  87910. if (header.id_length + offset > data.length) {
  87911. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87912. return;
  87913. }
  87914. // Skip not needed data
  87915. offset += header.id_length;
  87916. var use_rle = false;
  87917. var use_pal = false;
  87918. var use_grey = false;
  87919. // Get some informations.
  87920. switch (header.image_type) {
  87921. case TGATools._TYPE_RLE_INDEXED:
  87922. use_rle = true;
  87923. case TGATools._TYPE_INDEXED:
  87924. use_pal = true;
  87925. break;
  87926. case TGATools._TYPE_RLE_RGB:
  87927. use_rle = true;
  87928. case TGATools._TYPE_RGB:
  87929. // use_rgb = true;
  87930. break;
  87931. case TGATools._TYPE_RLE_GREY:
  87932. use_rle = true;
  87933. case TGATools._TYPE_GREY:
  87934. use_grey = true;
  87935. break;
  87936. }
  87937. var pixel_data;
  87938. // var numAlphaBits = header.flags & 0xf;
  87939. var pixel_size = header.pixel_size >> 3;
  87940. var pixel_total = header.width * header.height * pixel_size;
  87941. // Read palettes
  87942. var palettes;
  87943. if (use_pal) {
  87944. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87945. }
  87946. // Read LRE
  87947. if (use_rle) {
  87948. pixel_data = new Uint8Array(pixel_total);
  87949. var c, count, i;
  87950. var localOffset = 0;
  87951. var pixels = new Uint8Array(pixel_size);
  87952. while (offset < pixel_total && localOffset < pixel_total) {
  87953. c = data[offset++];
  87954. count = (c & 0x7f) + 1;
  87955. // RLE pixels
  87956. if (c & 0x80) {
  87957. // Bind pixel tmp array
  87958. for (i = 0; i < pixel_size; ++i) {
  87959. pixels[i] = data[offset++];
  87960. }
  87961. // Copy pixel array
  87962. for (i = 0; i < count; ++i) {
  87963. pixel_data.set(pixels, localOffset + i * pixel_size);
  87964. }
  87965. localOffset += pixel_size * count;
  87966. }
  87967. // Raw pixels
  87968. else {
  87969. count *= pixel_size;
  87970. for (i = 0; i < count; ++i) {
  87971. pixel_data[localOffset + i] = data[offset++];
  87972. }
  87973. localOffset += count;
  87974. }
  87975. }
  87976. }
  87977. // RAW Pixels
  87978. else {
  87979. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87980. }
  87981. // Load to texture
  87982. var x_start, y_start, x_step, y_step, y_end, x_end;
  87983. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87984. default:
  87985. case TGATools._ORIGIN_UL:
  87986. x_start = 0;
  87987. x_step = 1;
  87988. x_end = header.width;
  87989. y_start = 0;
  87990. y_step = 1;
  87991. y_end = header.height;
  87992. break;
  87993. case TGATools._ORIGIN_BL:
  87994. x_start = 0;
  87995. x_step = 1;
  87996. x_end = header.width;
  87997. y_start = header.height - 1;
  87998. y_step = -1;
  87999. y_end = -1;
  88000. break;
  88001. case TGATools._ORIGIN_UR:
  88002. x_start = header.width - 1;
  88003. x_step = -1;
  88004. x_end = -1;
  88005. y_start = 0;
  88006. y_step = 1;
  88007. y_end = header.height;
  88008. break;
  88009. case TGATools._ORIGIN_BR:
  88010. x_start = header.width - 1;
  88011. x_step = -1;
  88012. x_end = -1;
  88013. y_start = header.height - 1;
  88014. y_step = -1;
  88015. y_end = -1;
  88016. break;
  88017. }
  88018. // Load the specify method
  88019. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  88020. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  88021. var engine = texture.getEngine();
  88022. engine._uploadDataToTextureDirectly(texture, imageData);
  88023. };
  88024. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88025. var image = pixel_data, colormap = palettes;
  88026. var width = header.width, height = header.height;
  88027. var color, i = 0, x, y;
  88028. var imageData = new Uint8Array(width * height * 4);
  88029. for (y = y_start; y !== y_end; y += y_step) {
  88030. for (x = x_start; x !== x_end; x += x_step, i++) {
  88031. color = image[i];
  88032. imageData[(x + width * y) * 4 + 3] = 255;
  88033. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  88034. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  88035. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  88036. }
  88037. }
  88038. return imageData;
  88039. };
  88040. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88041. var image = pixel_data;
  88042. var width = header.width, height = header.height;
  88043. var color, i = 0, x, y;
  88044. var imageData = new Uint8Array(width * height * 4);
  88045. for (y = y_start; y !== y_end; y += y_step) {
  88046. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88047. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  88048. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  88049. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  88050. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  88051. imageData[(x + width * y) * 4 + 0] = r;
  88052. imageData[(x + width * y) * 4 + 1] = g;
  88053. imageData[(x + width * y) * 4 + 2] = b;
  88054. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  88055. }
  88056. }
  88057. return imageData;
  88058. };
  88059. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88060. var image = pixel_data;
  88061. var width = header.width, height = header.height;
  88062. var i = 0, x, y;
  88063. var imageData = new Uint8Array(width * height * 4);
  88064. for (y = y_start; y !== y_end; y += y_step) {
  88065. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  88066. imageData[(x + width * y) * 4 + 3] = 255;
  88067. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88068. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88069. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88070. }
  88071. }
  88072. return imageData;
  88073. };
  88074. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88075. var image = pixel_data;
  88076. var width = header.width, height = header.height;
  88077. var i = 0, x, y;
  88078. var imageData = new Uint8Array(width * height * 4);
  88079. for (y = y_start; y !== y_end; y += y_step) {
  88080. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  88081. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88082. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  88083. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  88084. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  88085. }
  88086. }
  88087. return imageData;
  88088. };
  88089. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88090. var image = pixel_data;
  88091. var width = header.width, height = header.height;
  88092. var color, i = 0, x, y;
  88093. var imageData = new Uint8Array(width * height * 4);
  88094. for (y = y_start; y !== y_end; y += y_step) {
  88095. for (x = x_start; x !== x_end; x += x_step, i++) {
  88096. color = image[i];
  88097. imageData[(x + width * y) * 4 + 0] = color;
  88098. imageData[(x + width * y) * 4 + 1] = color;
  88099. imageData[(x + width * y) * 4 + 2] = color;
  88100. imageData[(x + width * y) * 4 + 3] = 255;
  88101. }
  88102. }
  88103. return imageData;
  88104. };
  88105. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  88106. var image = pixel_data;
  88107. var width = header.width, height = header.height;
  88108. var i = 0, x, y;
  88109. var imageData = new Uint8Array(width * height * 4);
  88110. for (y = y_start; y !== y_end; y += y_step) {
  88111. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  88112. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  88113. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  88114. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  88115. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  88116. }
  88117. }
  88118. return imageData;
  88119. };
  88120. //private static _TYPE_NO_DATA = 0;
  88121. TGATools._TYPE_INDEXED = 1;
  88122. TGATools._TYPE_RGB = 2;
  88123. TGATools._TYPE_GREY = 3;
  88124. TGATools._TYPE_RLE_INDEXED = 9;
  88125. TGATools._TYPE_RLE_RGB = 10;
  88126. TGATools._TYPE_RLE_GREY = 11;
  88127. TGATools._ORIGIN_MASK = 0x30;
  88128. TGATools._ORIGIN_SHIFT = 0x04;
  88129. TGATools._ORIGIN_BL = 0x00;
  88130. TGATools._ORIGIN_BR = 0x01;
  88131. TGATools._ORIGIN_UL = 0x02;
  88132. TGATools._ORIGIN_UR = 0x03;
  88133. return TGATools;
  88134. }());
  88135. BABYLON.TGATools = TGATools;
  88136. })(BABYLON || (BABYLON = {}));
  88137. //# sourceMappingURL=babylon.tga.js.map
  88138. var BABYLON;
  88139. (function (BABYLON) {
  88140. /**
  88141. * Implementation of the TGA Texture Loader.
  88142. */
  88143. var TGATextureLoader = /** @class */ (function () {
  88144. function TGATextureLoader() {
  88145. /**
  88146. * Defines wether the loader supports cascade loading the different faces.
  88147. */
  88148. this.supportCascades = false;
  88149. }
  88150. /**
  88151. * This returns if the loader support the current file information.
  88152. * @param extension defines the file extension of the file being loaded
  88153. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88154. * @param fallback defines the fallback internal texture if any
  88155. * @param isBase64 defines whether the texture is encoded as a base64
  88156. * @param isBuffer defines whether the texture data are stored as a buffer
  88157. * @returns true if the loader can load the specified file
  88158. */
  88159. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88160. return extension.indexOf(".tga") === 0;
  88161. };
  88162. /**
  88163. * Transform the url before loading if required.
  88164. * @param rootUrl the url of the texture
  88165. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88166. * @returns the transformed texture
  88167. */
  88168. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88169. return rootUrl;
  88170. };
  88171. /**
  88172. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88173. * @param rootUrl the url of the texture
  88174. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88175. * @returns the fallback texture
  88176. */
  88177. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88178. return null;
  88179. };
  88180. /**
  88181. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88182. * @param data contains the texture data
  88183. * @param texture defines the BabylonJS internal texture
  88184. * @param createPolynomials will be true if polynomials have been requested
  88185. * @param onLoad defines the callback to trigger once the texture is ready
  88186. * @param onError defines the callback to trigger in case of error
  88187. */
  88188. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88189. throw ".env not supported in Cube.";
  88190. };
  88191. /**
  88192. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88193. * @param data contains the texture data
  88194. * @param texture defines the BabylonJS internal texture
  88195. * @param callback defines the method to call once ready to upload
  88196. */
  88197. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  88198. var uintData = new Uint8Array(data);
  88199. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  88200. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  88201. BABYLON.TGATools.UploadContent(texture, uintData);
  88202. });
  88203. };
  88204. return TGATextureLoader;
  88205. }());
  88206. // Register the loader.
  88207. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  88208. })(BABYLON || (BABYLON = {}));
  88209. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  88210. var BABYLON;
  88211. (function (BABYLON) {
  88212. /**
  88213. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  88214. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  88215. */
  88216. var KhronosTextureContainer = /** @class */ (function () {
  88217. /**
  88218. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  88219. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  88220. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  88221. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  88222. */
  88223. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  88224. this.arrayBuffer = arrayBuffer;
  88225. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  88226. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  88227. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  88228. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  88229. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  88230. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  88231. BABYLON.Tools.Error("texture missing KTX identifier");
  88232. return;
  88233. }
  88234. // load the reset of the header in native 32 bit int
  88235. var header = new Int32Array(this.arrayBuffer, 12, 13);
  88236. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  88237. var oppositeEndianess = header[0] === 0x01020304;
  88238. // read all the header elements in order they exist in the file, without modification (sans endainness)
  88239. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  88240. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  88241. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  88242. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  88243. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  88244. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  88245. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  88246. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  88247. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  88248. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  88249. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  88250. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  88251. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  88252. if (this.glType !== 0) {
  88253. BABYLON.Tools.Error("only compressed formats currently supported");
  88254. return;
  88255. }
  88256. else {
  88257. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  88258. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  88259. }
  88260. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  88261. BABYLON.Tools.Error("only 2D textures currently supported");
  88262. return;
  88263. }
  88264. if (this.numberOfArrayElements !== 0) {
  88265. BABYLON.Tools.Error("texture arrays not currently supported");
  88266. return;
  88267. }
  88268. if (this.numberOfFaces !== facesExpected) {
  88269. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  88270. return;
  88271. }
  88272. // we now have a completely validated file, so could use existence of loadType as success
  88273. // would need to make this more elaborate & adjust checks above to support more than one load type
  88274. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  88275. }
  88276. // not as fast hardware based, but will probably never need to use
  88277. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  88278. return ((val & 0xFF) << 24)
  88279. | ((val & 0xFF00) << 8)
  88280. | ((val >> 8) & 0xFF00)
  88281. | ((val >> 24) & 0xFF);
  88282. };
  88283. /**
  88284. * Uploads KTX content to a Babylon Texture.
  88285. * It is assumed that the texture has already been created & is currently bound
  88286. * @hidden
  88287. */
  88288. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  88289. switch (this.loadType) {
  88290. case KhronosTextureContainer.COMPRESSED_2D:
  88291. this._upload2DCompressedLevels(texture, loadMipmaps);
  88292. break;
  88293. case KhronosTextureContainer.TEX_2D:
  88294. case KhronosTextureContainer.COMPRESSED_3D:
  88295. case KhronosTextureContainer.TEX_3D:
  88296. }
  88297. };
  88298. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  88299. // initialize width & height for level 1
  88300. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  88301. var width = this.pixelWidth;
  88302. var height = this.pixelHeight;
  88303. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  88304. for (var level = 0; level < mipmapCount; level++) {
  88305. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  88306. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  88307. for (var face = 0; face < this.numberOfFaces; face++) {
  88308. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  88309. var engine = texture.getEngine();
  88310. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  88311. dataOffset += imageSize; // add size of the image for the next face/mipmap
  88312. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  88313. }
  88314. width = Math.max(1.0, width * 0.5);
  88315. height = Math.max(1.0, height * 0.5);
  88316. }
  88317. };
  88318. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  88319. // load types
  88320. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  88321. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  88322. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  88323. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  88324. return KhronosTextureContainer;
  88325. }());
  88326. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  88327. })(BABYLON || (BABYLON = {}));
  88328. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  88329. var BABYLON;
  88330. (function (BABYLON) {
  88331. /**
  88332. * Implementation of the KTX Texture Loader.
  88333. */
  88334. var KTXTextureLoader = /** @class */ (function () {
  88335. function KTXTextureLoader() {
  88336. /**
  88337. * Defines wether the loader supports cascade loading the different faces.
  88338. */
  88339. this.supportCascades = false;
  88340. }
  88341. /**
  88342. * This returns if the loader support the current file information.
  88343. * @param extension defines the file extension of the file being loaded
  88344. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88345. * @param fallback defines the fallback internal texture if any
  88346. * @param isBase64 defines whether the texture is encoded as a base64
  88347. * @param isBuffer defines whether the texture data are stored as a buffer
  88348. * @returns true if the loader can load the specified file
  88349. */
  88350. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88351. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  88352. return true;
  88353. }
  88354. return false;
  88355. };
  88356. /**
  88357. * Transform the url before loading if required.
  88358. * @param rootUrl the url of the texture
  88359. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88360. * @returns the transformed texture
  88361. */
  88362. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88363. var lastDot = rootUrl.lastIndexOf('.');
  88364. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  88365. };
  88366. /**
  88367. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88368. * @param rootUrl the url of the texture
  88369. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88370. * @returns the fallback texture
  88371. */
  88372. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88373. // remove the format appended to the rootUrl in the original createCubeTexture call.
  88374. var exp = new RegExp("" + textureFormatInUse + "$");
  88375. return rootUrl.replace(exp, "");
  88376. };
  88377. /**
  88378. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88379. * @param data contains the texture data
  88380. * @param texture defines the BabylonJS internal texture
  88381. * @param createPolynomials will be true if polynomials have been requested
  88382. * @param onLoad defines the callback to trigger once the texture is ready
  88383. * @param onError defines the callback to trigger in case of error
  88384. */
  88385. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88386. if (Array.isArray(data)) {
  88387. return;
  88388. }
  88389. var engine = texture.getEngine();
  88390. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  88391. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  88392. engine._unpackFlipY(true);
  88393. ktx.uploadLevels(texture, texture.generateMipMaps);
  88394. texture.width = ktx.pixelWidth;
  88395. texture.height = ktx.pixelHeight;
  88396. engine._setCubeMapTextureParams(loadMipmap);
  88397. texture.isReady = true;
  88398. };
  88399. /**
  88400. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88401. * @param data contains the texture data
  88402. * @param texture defines the BabylonJS internal texture
  88403. * @param callback defines the method to call once ready to upload
  88404. */
  88405. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  88406. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  88407. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  88408. ktx.uploadLevels(texture, texture.generateMipMaps);
  88409. });
  88410. };
  88411. return KTXTextureLoader;
  88412. }());
  88413. // Register the loader.
  88414. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  88415. })(BABYLON || (BABYLON = {}));
  88416. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  88417. var BABYLON;
  88418. (function (BABYLON) {
  88419. /**
  88420. * Sets of helpers addressing the serialization and deserialization of environment texture
  88421. * stored in a BabylonJS env file.
  88422. * Those files are usually stored as .env files.
  88423. */
  88424. var EnvironmentTextureTools = /** @class */ (function () {
  88425. function EnvironmentTextureTools() {
  88426. }
  88427. /**
  88428. * Gets the environment info from an env file.
  88429. * @param data The array buffer containing the .env bytes.
  88430. * @returns the environment file info (the json header) if successfully parsed.
  88431. */
  88432. EnvironmentTextureTools.GetEnvInfo = function (data) {
  88433. var dataView = new DataView(data);
  88434. var pos = 0;
  88435. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88436. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  88437. BABYLON.Tools.Error('Not a babylon environment map');
  88438. return null;
  88439. }
  88440. }
  88441. // Read json manifest - collect characters up to null terminator
  88442. var manifestString = '';
  88443. var charCode = 0x00;
  88444. while ((charCode = dataView.getUint8(pos++))) {
  88445. manifestString += String.fromCharCode(charCode);
  88446. }
  88447. var manifest = JSON.parse(manifestString);
  88448. if (manifest.specular) {
  88449. // Extend the header with the position of the payload.
  88450. manifest.specular.specularDataPosition = pos;
  88451. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  88452. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  88453. }
  88454. return manifest;
  88455. };
  88456. /**
  88457. * Creates an environment texture from a loaded cube texture.
  88458. * @param texture defines the cube texture to convert in env file
  88459. * @return a promise containing the environment data if succesfull.
  88460. */
  88461. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  88462. var _this = this;
  88463. var internalTexture = texture.getInternalTexture();
  88464. if (!internalTexture) {
  88465. return Promise.reject("The cube texture is invalid.");
  88466. }
  88467. if (!texture._prefiltered) {
  88468. return Promise.reject("The cube texture is invalid (not prefiltered).");
  88469. }
  88470. var engine = internalTexture.getEngine();
  88471. if (engine && engine.premultipliedAlpha) {
  88472. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  88473. }
  88474. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  88475. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  88476. }
  88477. var canvas = engine.getRenderingCanvas();
  88478. if (!canvas) {
  88479. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  88480. }
  88481. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88482. if (!engine.getCaps().textureFloatRender) {
  88483. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88484. if (!engine.getCaps().textureHalfFloatRender) {
  88485. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  88486. }
  88487. }
  88488. var cubeWidth = internalTexture.width;
  88489. var hostingScene = new BABYLON.Scene(engine);
  88490. var specularTextures = {};
  88491. var promises = [];
  88492. // Read and collect all mipmaps data from the cube.
  88493. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  88494. mipmapsCount = Math.round(mipmapsCount);
  88495. var _loop_1 = function (i) {
  88496. var faceWidth = Math.pow(2, mipmapsCount - i);
  88497. var _loop_2 = function (face) {
  88498. var data = texture.readPixels(face, i);
  88499. // Creates a temp texture with the face data.
  88500. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  88501. // And rgbdEncode them.
  88502. var promise = new Promise(function (resolve, reject) {
  88503. 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);
  88504. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88505. rgbdPostProcess.onApply = function (effect) {
  88506. effect._bindTexture("textureSampler", tempTexture);
  88507. };
  88508. // As the process needs to happen on the main canvas, keep track of the current size
  88509. var currentW = engine.getRenderWidth();
  88510. var currentH = engine.getRenderHeight();
  88511. // Set the desired size for the texture
  88512. engine.setSize(faceWidth, faceWidth);
  88513. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  88514. // Reading datas from WebGL
  88515. BABYLON.Tools.ToBlob(canvas, function (blob) {
  88516. var fileReader = new FileReader();
  88517. fileReader.onload = function (event) {
  88518. var arrayBuffer = event.target.result;
  88519. specularTextures[i * 6 + face] = arrayBuffer;
  88520. resolve();
  88521. };
  88522. fileReader.readAsArrayBuffer(blob);
  88523. });
  88524. // Reapply the previous canvas size
  88525. engine.setSize(currentW, currentH);
  88526. });
  88527. });
  88528. promises.push(promise);
  88529. };
  88530. // All faces of the cube.
  88531. for (var face = 0; face < 6; face++) {
  88532. _loop_2(face);
  88533. }
  88534. };
  88535. for (var i = 0; i <= mipmapsCount; i++) {
  88536. _loop_1(i);
  88537. }
  88538. // Once all the textures haves been collected as RGBD stored in PNGs
  88539. return Promise.all(promises).then(function () {
  88540. // We can delete the hosting scene keeping track of all the creation objects
  88541. hostingScene.dispose();
  88542. // Creates the json header for the env texture
  88543. var info = {
  88544. version: 1,
  88545. width: cubeWidth,
  88546. irradiance: _this._CreateEnvTextureIrradiance(texture),
  88547. specular: {
  88548. mipmaps: [],
  88549. lodGenerationScale: texture.lodGenerationScale
  88550. }
  88551. };
  88552. // Sets the specular image data information
  88553. var position = 0;
  88554. for (var i = 0; i <= mipmapsCount; i++) {
  88555. for (var face = 0; face < 6; face++) {
  88556. var byteLength = specularTextures[i * 6 + face].byteLength;
  88557. info.specular.mipmaps.push({
  88558. length: byteLength,
  88559. position: position
  88560. });
  88561. position += byteLength;
  88562. }
  88563. }
  88564. // Encode the JSON as an array buffer
  88565. var infoString = JSON.stringify(info);
  88566. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  88567. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  88568. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  88569. infoView[i] = infoString.charCodeAt(i);
  88570. }
  88571. // Ends up with a null terminator for easier parsing
  88572. infoView[infoString.length] = 0x00;
  88573. // Computes the final required size and creates the storage
  88574. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  88575. var finalBuffer = new ArrayBuffer(totalSize);
  88576. var finalBufferView = new Uint8Array(finalBuffer);
  88577. var dataView = new DataView(finalBuffer);
  88578. // Copy the magic bytes identifying the file in
  88579. var pos = 0;
  88580. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  88581. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  88582. }
  88583. // Add the json info
  88584. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  88585. pos += infoBuffer.byteLength;
  88586. // Finally inserts the texture data
  88587. for (var i = 0; i <= mipmapsCount; i++) {
  88588. for (var face = 0; face < 6; face++) {
  88589. var dataBuffer = specularTextures[i * 6 + face];
  88590. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  88591. pos += dataBuffer.byteLength;
  88592. }
  88593. }
  88594. // Voila
  88595. return finalBuffer;
  88596. });
  88597. };
  88598. /**
  88599. * Creates a JSON representation of the spherical data.
  88600. * @param texture defines the texture containing the polynomials
  88601. * @return the JSON representation of the spherical info
  88602. */
  88603. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  88604. var polynmials = texture.sphericalPolynomial;
  88605. if (polynmials == null) {
  88606. return null;
  88607. }
  88608. return {
  88609. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  88610. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  88611. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  88612. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  88613. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  88614. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  88615. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  88616. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  88617. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  88618. };
  88619. };
  88620. /**
  88621. * Uploads the texture info contained in the env file to the GPU.
  88622. * @param texture defines the internal texture to upload to
  88623. * @param arrayBuffer defines the buffer cotaining the data to load
  88624. * @param info defines the texture info retrieved through the GetEnvInfo method
  88625. * @returns a promise
  88626. */
  88627. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  88628. if (info.version !== 1) {
  88629. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  88630. }
  88631. var specularInfo = info.specular;
  88632. if (!specularInfo) {
  88633. // Nothing else parsed so far
  88634. return Promise.resolve();
  88635. }
  88636. // Double checks the enclosed info
  88637. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  88638. mipmapsCount = Math.round(mipmapsCount) + 1;
  88639. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  88640. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  88641. }
  88642. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  88643. var imageData = new Array(mipmapsCount);
  88644. for (var i = 0; i < mipmapsCount; i++) {
  88645. imageData[i] = new Array(6);
  88646. for (var face = 0; face < 6; face++) {
  88647. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  88648. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  88649. }
  88650. }
  88651. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  88652. };
  88653. /**
  88654. * Uploads the levels of image data to the GPU.
  88655. * @param texture defines the internal texture to upload to
  88656. * @param imageData defines the array buffer views of image data [mipmap][face]
  88657. * @returns a promise
  88658. */
  88659. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  88660. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  88661. throw new Error("Texture size must be a power of two");
  88662. }
  88663. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  88664. // Gets everything ready.
  88665. var engine = texture.getEngine();
  88666. var expandTexture = false;
  88667. var generateNonLODTextures = false;
  88668. var rgbdPostProcess = null;
  88669. var cubeRtt = null;
  88670. var lodTextures = null;
  88671. var caps = engine.getCaps();
  88672. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  88673. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88674. texture.generateMipMaps = true;
  88675. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  88676. // Add extra process if texture lod is not supported
  88677. if (!caps.textureLOD) {
  88678. expandTexture = false;
  88679. generateNonLODTextures = true;
  88680. lodTextures = {};
  88681. }
  88682. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  88683. else if (engine.webGLVersion < 2) {
  88684. expandTexture = false;
  88685. }
  88686. // If half float available we can uncompress the texture
  88687. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  88688. expandTexture = true;
  88689. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88690. }
  88691. // If full float available we can uncompress the texture
  88692. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  88693. expandTexture = true;
  88694. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88695. }
  88696. // Expand the texture if possible
  88697. if (expandTexture) {
  88698. // Simply run through the decode PP
  88699. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  88700. texture._isRGBD = false;
  88701. texture.invertY = false;
  88702. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  88703. generateDepthBuffer: false,
  88704. generateMipMaps: true,
  88705. generateStencilBuffer: false,
  88706. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  88707. type: texture.type,
  88708. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  88709. });
  88710. }
  88711. else {
  88712. texture._isRGBD = true;
  88713. texture.invertY = true;
  88714. // In case of missing support, applies the same patch than DDS files.
  88715. if (generateNonLODTextures) {
  88716. var mipSlices = 3;
  88717. var scale = texture._lodGenerationScale;
  88718. var offset = texture._lodGenerationOffset;
  88719. for (var i = 0; i < mipSlices; i++) {
  88720. //compute LOD from even spacing in smoothness (matching shader calculation)
  88721. var smoothness = i / (mipSlices - 1);
  88722. var roughness = 1 - smoothness;
  88723. var minLODIndex = offset; // roughness = 0
  88724. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  88725. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  88726. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  88727. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  88728. glTextureFromLod.isCube = true;
  88729. glTextureFromLod.invertY = true;
  88730. glTextureFromLod.generateMipMaps = false;
  88731. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  88732. // Wrap in a base texture for easy binding.
  88733. var lodTexture = new BABYLON.BaseTexture(null);
  88734. lodTexture.isCube = true;
  88735. lodTexture._texture = glTextureFromLod;
  88736. lodTextures[mipmapIndex] = lodTexture;
  88737. switch (i) {
  88738. case 0:
  88739. texture._lodTextureLow = lodTexture;
  88740. break;
  88741. case 1:
  88742. texture._lodTextureMid = lodTexture;
  88743. break;
  88744. case 2:
  88745. texture._lodTextureHigh = lodTexture;
  88746. break;
  88747. }
  88748. }
  88749. }
  88750. }
  88751. var promises = [];
  88752. var _loop_3 = function (i) {
  88753. var _loop_4 = function (face) {
  88754. // Constructs an image element from image data
  88755. var bytes = imageData[i][face];
  88756. var blob = new Blob([bytes], { type: 'image/png' });
  88757. var url = URL.createObjectURL(blob);
  88758. var image = new Image();
  88759. image.src = url;
  88760. // Enqueue promise to upload to the texture.
  88761. var promise = new Promise(function (resolve, reject) {
  88762. image.onload = function () {
  88763. if (expandTexture) {
  88764. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  88765. reject(message);
  88766. }, image);
  88767. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  88768. // Uncompress the data to a RTT
  88769. rgbdPostProcess.onApply = function (effect) {
  88770. effect._bindTexture("textureSampler", tempTexture_1);
  88771. effect.setFloat2("scale", 1, 1);
  88772. };
  88773. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  88774. // Cleanup
  88775. engine.restoreDefaultFramebuffer();
  88776. tempTexture_1.dispose();
  88777. window.URL.revokeObjectURL(url);
  88778. resolve();
  88779. });
  88780. }
  88781. else {
  88782. engine._uploadImageToTexture(texture, image, face, i);
  88783. // Upload the face to the non lod texture support
  88784. if (generateNonLODTextures) {
  88785. var lodTexture = lodTextures[i];
  88786. if (lodTexture) {
  88787. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  88788. }
  88789. }
  88790. resolve();
  88791. }
  88792. };
  88793. image.onerror = function (error) {
  88794. reject(error);
  88795. };
  88796. });
  88797. promises.push(promise);
  88798. };
  88799. // All faces
  88800. for (var face = 0; face < 6; face++) {
  88801. _loop_4(face);
  88802. }
  88803. };
  88804. // All mipmaps up to provided number of images
  88805. for (var i = 0; i < imageData.length; i++) {
  88806. _loop_3(i);
  88807. }
  88808. // Fill remaining mipmaps with black textures.
  88809. if (imageData.length < mipmapsCount) {
  88810. var data = void 0;
  88811. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  88812. var dataLength = size * size * 4;
  88813. switch (texture.type) {
  88814. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  88815. data = new Uint8Array(dataLength);
  88816. break;
  88817. }
  88818. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  88819. data = new Uint16Array(dataLength);
  88820. break;
  88821. }
  88822. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  88823. data = new Float32Array(dataLength);
  88824. break;
  88825. }
  88826. }
  88827. for (var i = imageData.length; i < mipmapsCount; i++) {
  88828. for (var face = 0; face < 6; face++) {
  88829. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  88830. }
  88831. }
  88832. }
  88833. // Once all done, finishes the cleanup and return
  88834. return Promise.all(promises).then(function () {
  88835. // Release temp RTT.
  88836. if (cubeRtt) {
  88837. engine._releaseFramebufferObjects(cubeRtt);
  88838. cubeRtt._swapAndDie(texture);
  88839. }
  88840. // Release temp Post Process.
  88841. if (rgbdPostProcess) {
  88842. rgbdPostProcess.dispose();
  88843. }
  88844. // Flag internal texture as ready in case they are in use.
  88845. if (generateNonLODTextures) {
  88846. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  88847. texture._lodTextureHigh._texture.isReady = true;
  88848. }
  88849. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  88850. texture._lodTextureMid._texture.isReady = true;
  88851. }
  88852. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  88853. texture._lodTextureLow._texture.isReady = true;
  88854. }
  88855. }
  88856. });
  88857. };
  88858. /**
  88859. * Uploads spherical polynomials information to the texture.
  88860. * @param texture defines the texture we are trying to upload the information to
  88861. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  88862. */
  88863. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  88864. if (info.version !== 1) {
  88865. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  88866. }
  88867. var irradianceInfo = info.irradiance;
  88868. if (!irradianceInfo) {
  88869. return;
  88870. }
  88871. var sp = new BABYLON.SphericalPolynomial();
  88872. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  88873. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  88874. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  88875. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  88876. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  88877. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  88878. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  88879. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  88880. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  88881. texture._sphericalPolynomial = sp;
  88882. };
  88883. /**
  88884. * Magic number identifying the env file.
  88885. */
  88886. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  88887. return EnvironmentTextureTools;
  88888. }());
  88889. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  88890. })(BABYLON || (BABYLON = {}));
  88891. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  88892. var BABYLON;
  88893. (function (BABYLON) {
  88894. /**
  88895. * Implementation of the ENV Texture Loader.
  88896. */
  88897. var ENVTextureLoader = /** @class */ (function () {
  88898. function ENVTextureLoader() {
  88899. /**
  88900. * Defines wether the loader supports cascade loading the different faces.
  88901. */
  88902. this.supportCascades = false;
  88903. }
  88904. /**
  88905. * This returns if the loader support the current file information.
  88906. * @param extension defines the file extension of the file being loaded
  88907. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88908. * @param fallback defines the fallback internal texture if any
  88909. * @param isBase64 defines whether the texture is encoded as a base64
  88910. * @param isBuffer defines whether the texture data are stored as a buffer
  88911. * @returns true if the loader can load the specified file
  88912. */
  88913. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  88914. return extension.indexOf(".env") === 0;
  88915. };
  88916. /**
  88917. * Transform the url before loading if required.
  88918. * @param rootUrl the url of the texture
  88919. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88920. * @returns the transformed texture
  88921. */
  88922. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  88923. return rootUrl;
  88924. };
  88925. /**
  88926. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  88927. * @param rootUrl the url of the texture
  88928. * @param textureFormatInUse defines the current compressed format in use iun the engine
  88929. * @returns the fallback texture
  88930. */
  88931. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  88932. return null;
  88933. };
  88934. /**
  88935. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  88936. * @param data contains the texture data
  88937. * @param texture defines the BabylonJS internal texture
  88938. * @param createPolynomials will be true if polynomials have been requested
  88939. * @param onLoad defines the callback to trigger once the texture is ready
  88940. * @param onError defines the callback to trigger in case of error
  88941. */
  88942. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  88943. if (Array.isArray(data)) {
  88944. return;
  88945. }
  88946. data = data;
  88947. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  88948. if (info) {
  88949. texture.width = info.width;
  88950. texture.height = info.width;
  88951. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  88952. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  88953. texture.isReady = true;
  88954. if (onLoad) {
  88955. onLoad();
  88956. }
  88957. });
  88958. }
  88959. else if (onError) {
  88960. onError("Can not parse the environment file", null);
  88961. }
  88962. };
  88963. /**
  88964. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  88965. * @param data contains the texture data
  88966. * @param texture defines the BabylonJS internal texture
  88967. * @param callback defines the method to call once ready to upload
  88968. */
  88969. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  88970. throw ".env not supported in 2d.";
  88971. };
  88972. return ENVTextureLoader;
  88973. }());
  88974. // Register the loader.
  88975. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  88976. })(BABYLON || (BABYLON = {}));
  88977. //# sourceMappingURL=babylon.envTextureLoader.js.map
  88978. var BABYLON;
  88979. (function (BABYLON) {
  88980. /**
  88981. * Renders a layer on top of an existing scene
  88982. */
  88983. var UtilityLayerRenderer = /** @class */ (function () {
  88984. /**
  88985. * Instantiates a UtilityLayerRenderer
  88986. * @param originalScene the original scene that will be rendered on top of
  88987. */
  88988. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88989. var _this = this;
  88990. this.originalScene = originalScene;
  88991. this._pointerCaptures = {};
  88992. this._lastPointerEvents = {};
  88993. /**
  88994. * If the utility layer should automatically be rendered on top of existing scene
  88995. */
  88996. this.shouldRender = true;
  88997. /**
  88998. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88999. */
  89000. this.onlyCheckPointerDownEvents = true;
  89001. /**
  89002. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  89003. */
  89004. this.processAllEvents = false;
  89005. /**
  89006. * Observable raised when the pointer move from the utility layer scene to the main scene
  89007. */
  89008. this.onPointerOutObservable = new BABYLON.Observable();
  89009. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  89010. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  89011. this.utilityLayerScene._allowPostProcessClear = false;
  89012. originalScene.getEngine().scenes.pop();
  89013. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  89014. this.utilityLayerScene.detachControl();
  89015. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  89016. if (!_this.processAllEvents) {
  89017. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  89018. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  89019. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  89020. return;
  89021. }
  89022. }
  89023. var pointerEvent = (prePointerInfo.event);
  89024. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  89025. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89026. return;
  89027. }
  89028. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  89029. if (!prePointerInfo.ray && utilityScenePick) {
  89030. prePointerInfo.ray = utilityScenePick.ray;
  89031. }
  89032. // always fire the prepointer oversvable
  89033. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  89034. // allow every non pointer down event to flow to the utility layer
  89035. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  89036. if (!prePointerInfo.skipOnPointerObservable) {
  89037. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89038. }
  89039. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  89040. _this._pointerCaptures[pointerEvent.pointerId] = false;
  89041. }
  89042. return;
  89043. }
  89044. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  89045. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  89046. if (utilityScenePick && utilityScenePick.hit) {
  89047. if (!prePointerInfo.skipOnPointerObservable) {
  89048. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  89049. }
  89050. prePointerInfo.skipOnPointerObservable = true;
  89051. }
  89052. }
  89053. else {
  89054. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  89055. var pointerEvent_1 = (prePointerInfo.event);
  89056. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  89057. if (originalScenePick && utilityScenePick) {
  89058. // No pick in utility scene
  89059. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  89060. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89061. // We touched an utility mesh present in the main scene
  89062. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89063. prePointerInfo.skipOnPointerObservable = true;
  89064. }
  89065. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89066. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  89067. }
  89068. }
  89069. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  89070. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  89071. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  89072. // If a previous utility layer set this, do not unset this
  89073. if (!prePointerInfo.skipOnPointerObservable) {
  89074. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  89075. }
  89076. }
  89077. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  89078. // We have a pick in both scenes but main is closer than utility
  89079. // We touched an utility mesh present in the main scene
  89080. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  89081. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  89082. prePointerInfo.skipOnPointerObservable = true;
  89083. }
  89084. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  89085. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  89086. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  89087. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  89088. }
  89089. }
  89090. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  89091. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  89092. }
  89093. }
  89094. }
  89095. });
  89096. // Render directly on top of existing scene without clearing
  89097. this.utilityLayerScene.autoClear = false;
  89098. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  89099. if (_this.shouldRender) {
  89100. _this.render();
  89101. }
  89102. });
  89103. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  89104. _this.dispose();
  89105. });
  89106. this._updateCamera();
  89107. }
  89108. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  89109. /**
  89110. * 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)
  89111. */
  89112. get: function () {
  89113. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  89114. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89115. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89116. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89117. });
  89118. }
  89119. return UtilityLayerRenderer._DefaultUtilityLayer;
  89120. },
  89121. enumerable: true,
  89122. configurable: true
  89123. });
  89124. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  89125. /**
  89126. * 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)
  89127. */
  89128. get: function () {
  89129. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  89130. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  89131. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  89132. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  89133. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89134. });
  89135. }
  89136. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  89137. },
  89138. enumerable: true,
  89139. configurable: true
  89140. });
  89141. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  89142. if (!prePointerInfo.skipOnPointerObservable) {
  89143. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  89144. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  89145. }
  89146. };
  89147. /**
  89148. * Renders the utility layers scene on top of the original scene
  89149. */
  89150. UtilityLayerRenderer.prototype.render = function () {
  89151. this._updateCamera();
  89152. if (this.utilityLayerScene.activeCamera) {
  89153. // Set the camera's scene to utility layers scene
  89154. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  89155. var camera = this.utilityLayerScene.activeCamera;
  89156. camera._scene = this.utilityLayerScene;
  89157. if (camera.leftCamera) {
  89158. camera.leftCamera._scene = this.utilityLayerScene;
  89159. }
  89160. if (camera.rightCamera) {
  89161. camera.rightCamera._scene = this.utilityLayerScene;
  89162. }
  89163. this.utilityLayerScene.render(false);
  89164. // Reset camera's scene back to original
  89165. camera._scene = oldScene;
  89166. if (camera.leftCamera) {
  89167. camera.leftCamera._scene = oldScene;
  89168. }
  89169. if (camera.rightCamera) {
  89170. camera.rightCamera._scene = oldScene;
  89171. }
  89172. }
  89173. };
  89174. /**
  89175. * Disposes of the renderer
  89176. */
  89177. UtilityLayerRenderer.prototype.dispose = function () {
  89178. this.onPointerOutObservable.clear();
  89179. if (this._afterRenderObserver) {
  89180. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  89181. }
  89182. if (this._sceneDisposeObserver) {
  89183. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89184. }
  89185. if (this._originalPointerObserver) {
  89186. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  89187. }
  89188. this.utilityLayerScene.dispose();
  89189. };
  89190. UtilityLayerRenderer.prototype._updateCamera = function () {
  89191. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  89192. };
  89193. UtilityLayerRenderer._DefaultUtilityLayer = null;
  89194. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  89195. return UtilityLayerRenderer;
  89196. }());
  89197. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  89198. })(BABYLON || (BABYLON = {}));
  89199. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  89200. //# sourceMappingURL=babylon.behavior.js.map
  89201. var BABYLON;
  89202. (function (BABYLON) {
  89203. /**
  89204. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  89205. */
  89206. var PointerDragBehavior = /** @class */ (function () {
  89207. /**
  89208. * Creates a pointer drag behavior that can be attached to a mesh
  89209. * @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)
  89210. */
  89211. function PointerDragBehavior(options) {
  89212. /**
  89213. * 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)
  89214. */
  89215. this.maxDragAngle = 0;
  89216. /**
  89217. * @hidden
  89218. */
  89219. this._useAlternatePickedPointAboveMaxDragAngle = false;
  89220. /**
  89221. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89222. */
  89223. this.currentDraggingPointerID = -1;
  89224. /**
  89225. * If the behavior is currently in a dragging state
  89226. */
  89227. this.dragging = false;
  89228. /**
  89229. * 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)
  89230. */
  89231. this.dragDeltaRatio = 0.2;
  89232. /**
  89233. * If the drag plane orientation should be updated during the dragging (Default: true)
  89234. */
  89235. this.updateDragPlane = true;
  89236. // Debug mode will display drag planes to help visualize behavior
  89237. this._debugMode = false;
  89238. this._moving = false;
  89239. /**
  89240. * Fires each time the attached mesh is dragged with the pointer
  89241. * * delta between last drag position and current drag position in world space
  89242. * * dragDistance along the drag axis
  89243. * * dragPlaneNormal normal of the current drag plane used during the drag
  89244. * * dragPlanePoint in world space where the drag intersects the drag plane
  89245. */
  89246. this.onDragObservable = new BABYLON.Observable();
  89247. /**
  89248. * Fires each time a drag begins (eg. mouse down on mesh)
  89249. */
  89250. this.onDragStartObservable = new BABYLON.Observable();
  89251. /**
  89252. * Fires each time a drag ends (eg. mouse release after drag)
  89253. */
  89254. this.onDragEndObservable = new BABYLON.Observable();
  89255. /**
  89256. * If the attached mesh should be moved when dragged
  89257. */
  89258. this.moveAttached = true;
  89259. /**
  89260. * If the drag behavior will react to drag events (Default: true)
  89261. */
  89262. this.enabled = true;
  89263. /**
  89264. * If camera controls should be detached during the drag
  89265. */
  89266. this.detachCameraControls = true;
  89267. /**
  89268. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  89269. */
  89270. this.useObjectOrienationForDragging = true;
  89271. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89272. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  89273. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  89274. // Variables to avoid instantiation in the below method
  89275. this._pointA = new BABYLON.Vector3(0, 0, 0);
  89276. this._pointB = new BABYLON.Vector3(0, 0, 0);
  89277. this._pointC = new BABYLON.Vector3(0, 0, 0);
  89278. this._lineA = new BABYLON.Vector3(0, 0, 0);
  89279. this._lineB = new BABYLON.Vector3(0, 0, 0);
  89280. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  89281. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  89282. this._options = options ? options : {};
  89283. var optionCount = 0;
  89284. if (this._options.dragAxis) {
  89285. optionCount++;
  89286. }
  89287. if (this._options.dragPlaneNormal) {
  89288. optionCount++;
  89289. }
  89290. if (optionCount > 1) {
  89291. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89292. }
  89293. }
  89294. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89295. /**
  89296. * The name of the behavior
  89297. */
  89298. get: function () {
  89299. return "PointerDrag";
  89300. },
  89301. enumerable: true,
  89302. configurable: true
  89303. });
  89304. /**
  89305. * Initializes the behavior
  89306. */
  89307. PointerDragBehavior.prototype.init = function () { };
  89308. /**
  89309. * Attaches the drag behavior the passed in mesh
  89310. * @param ownerNode The mesh that will be dragged around once attached
  89311. */
  89312. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89313. var _this = this;
  89314. this._scene = ownerNode.getScene();
  89315. this._attachedNode = ownerNode;
  89316. // Initialize drag plane to not interfere with existing scene
  89317. if (!PointerDragBehavior._planeScene) {
  89318. if (this._debugMode) {
  89319. PointerDragBehavior._planeScene = this._scene;
  89320. }
  89321. else {
  89322. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89323. PointerDragBehavior._planeScene.detachControl();
  89324. this._scene.getEngine().scenes.pop();
  89325. this._scene.onDisposeObservable.addOnce(function () {
  89326. PointerDragBehavior._planeScene.dispose();
  89327. PointerDragBehavior._planeScene = null;
  89328. });
  89329. }
  89330. }
  89331. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89332. // State of the drag
  89333. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89334. var delta = new BABYLON.Vector3(0, 0, 0);
  89335. var dragLength = 0;
  89336. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89337. var pickPredicate = function (m) {
  89338. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89339. };
  89340. var attachedElement = null;
  89341. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89342. if (!_this.enabled) {
  89343. return;
  89344. }
  89345. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89346. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89347. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89348. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89349. if (pickedPoint) {
  89350. _this.dragging = true;
  89351. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89352. _this.lastDragPosition.copyFrom(pickedPoint);
  89353. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89354. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89355. // Detatch camera controls
  89356. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89357. if (_this._scene.activeCamera.inputs.attachedElement) {
  89358. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89359. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89360. }
  89361. else {
  89362. attachedElement = null;
  89363. }
  89364. }
  89365. }
  89366. }
  89367. }
  89368. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89369. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89370. _this.releaseDrag();
  89371. // Reattach camera controls
  89372. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89373. _this._scene.activeCamera.attachControl(attachedElement, true);
  89374. }
  89375. }
  89376. }
  89377. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89378. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89379. _this._moving = true;
  89380. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89381. if (pickedPoint) {
  89382. if (_this.updateDragPlane) {
  89383. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89384. }
  89385. // depending on the drag mode option drag accordingly
  89386. if (_this._options.dragAxis) {
  89387. // Convert local drag axis to world
  89388. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89389. // Project delta drag from the drag plane onto the drag axis
  89390. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89391. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89392. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89393. }
  89394. else {
  89395. dragLength = delta.length();
  89396. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89397. }
  89398. targetPosition.addInPlace(delta);
  89399. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89400. _this.lastDragPosition.copyFrom(pickedPoint);
  89401. }
  89402. }
  89403. }
  89404. });
  89405. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89406. if (_this._moving && _this.moveAttached) {
  89407. // Slowly move mesh to avoid jitter
  89408. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89409. _this._tmpVector.scaleInPlace(0.2);
  89410. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89411. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89412. }
  89413. });
  89414. };
  89415. PointerDragBehavior.prototype.releaseDrag = function () {
  89416. this.dragging = false;
  89417. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89418. this.currentDraggingPointerID = -1;
  89419. this._moving = false;
  89420. };
  89421. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89422. var _this = this;
  89423. if (!ray) {
  89424. return null;
  89425. }
  89426. // Calculate angle between plane normal and ray
  89427. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89428. // Correct if ray is casted from oposite side
  89429. if (angle > Math.PI / 2) {
  89430. angle = Math.PI - angle;
  89431. }
  89432. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89433. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89434. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89435. // Invert ray direction along the towards object axis
  89436. this._tmpVector.copyFrom(ray.direction);
  89437. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89438. this._alternatePickedPoint.normalize();
  89439. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89440. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89441. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89442. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89443. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89444. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89445. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89446. return this._alternatePickedPoint;
  89447. }
  89448. else {
  89449. return null;
  89450. }
  89451. }
  89452. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89453. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89454. return pickResult.pickedPoint;
  89455. }
  89456. else {
  89457. return null;
  89458. }
  89459. };
  89460. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89461. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89462. this._pointA.copyFrom(dragPlanePosition);
  89463. if (this._options.dragAxis) {
  89464. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  89465. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89466. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89467. ray.origin.subtractToRef(this._pointA, this._pointC);
  89468. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89469. // Get perpendicular line from direction to camera and drag axis
  89470. this._pointB.subtractToRef(this._pointA, this._lineA);
  89471. this._pointC.subtractToRef(this._pointA, this._lineB);
  89472. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89473. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89474. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89475. this._lookAt.normalize();
  89476. this._dragPlane.position.copyFrom(this._pointA);
  89477. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89478. this._dragPlane.lookAt(this._lookAt);
  89479. }
  89480. else if (this._options.dragPlaneNormal) {
  89481. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  89482. this._dragPlane.position.copyFrom(this._pointA);
  89483. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89484. this._dragPlane.lookAt(this._lookAt);
  89485. }
  89486. else {
  89487. this._dragPlane.position.copyFrom(this._pointA);
  89488. this._dragPlane.lookAt(ray.origin);
  89489. }
  89490. this._dragPlane.computeWorldMatrix(true);
  89491. };
  89492. /**
  89493. * Detaches the behavior from the mesh
  89494. */
  89495. PointerDragBehavior.prototype.detach = function () {
  89496. if (this._pointerObserver) {
  89497. this._scene.onPointerObservable.remove(this._pointerObserver);
  89498. }
  89499. if (this._beforeRenderObserver) {
  89500. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89501. }
  89502. };
  89503. return PointerDragBehavior;
  89504. }());
  89505. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89506. })(BABYLON || (BABYLON = {}));
  89507. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89508. var BABYLON;
  89509. (function (BABYLON) {
  89510. /**
  89511. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89512. */
  89513. var MultiPointerScaleBehavior = /** @class */ (function () {
  89514. function MultiPointerScaleBehavior() {
  89515. this._startDistance = 0;
  89516. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89517. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89518. this._sceneRenderObserver = null;
  89519. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89520. this._dragBehaviorA.moveAttached = false;
  89521. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89522. this._dragBehaviorB.moveAttached = false;
  89523. }
  89524. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89525. /**
  89526. * The name of the behavior
  89527. */
  89528. get: function () {
  89529. return "MultiPointerScale";
  89530. },
  89531. enumerable: true,
  89532. configurable: true
  89533. });
  89534. /**
  89535. * Initializes the behavior
  89536. */
  89537. MultiPointerScaleBehavior.prototype.init = function () { };
  89538. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89539. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89540. };
  89541. /**
  89542. * Attaches the scale behavior the passed in mesh
  89543. * @param ownerNode The mesh that will be scaled around once attached
  89544. */
  89545. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89546. var _this = this;
  89547. this._ownerNode = ownerNode;
  89548. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89549. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89550. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89551. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89552. _this._dragBehaviorA.releaseDrag();
  89553. }
  89554. else {
  89555. _this._initialScale.copyFrom(ownerNode.scaling);
  89556. _this._startDistance = _this._getCurrentDistance();
  89557. }
  89558. }
  89559. });
  89560. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89561. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89562. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89563. _this._dragBehaviorB.releaseDrag();
  89564. }
  89565. else {
  89566. _this._initialScale.copyFrom(ownerNode.scaling);
  89567. _this._startDistance = _this._getCurrentDistance();
  89568. }
  89569. }
  89570. });
  89571. // Once both drag behaviors are active scale based on the distance between the two pointers
  89572. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89573. behavior.onDragObservable.add(function () {
  89574. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89575. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89576. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89577. }
  89578. });
  89579. });
  89580. ownerNode.addBehavior(this._dragBehaviorA);
  89581. ownerNode.addBehavior(this._dragBehaviorB);
  89582. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89583. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89584. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89585. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89586. if (change.length() > 0.01) {
  89587. ownerNode.scaling.addInPlace(change);
  89588. }
  89589. }
  89590. });
  89591. };
  89592. /**
  89593. * Detaches the behavior from the mesh
  89594. */
  89595. MultiPointerScaleBehavior.prototype.detach = function () {
  89596. var _this = this;
  89597. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89598. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89599. behavior.onDragStartObservable.clear();
  89600. behavior.onDragObservable.clear();
  89601. _this._ownerNode.removeBehavior(behavior);
  89602. });
  89603. };
  89604. return MultiPointerScaleBehavior;
  89605. }());
  89606. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89607. })(BABYLON || (BABYLON = {}));
  89608. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89609. var BABYLON;
  89610. (function (BABYLON) {
  89611. /**
  89612. * 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
  89613. */
  89614. var SixDofDragBehavior = /** @class */ (function () {
  89615. function SixDofDragBehavior() {
  89616. this._sceneRenderObserver = null;
  89617. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89618. this._moving = false;
  89619. this._startingOrientation = new BABYLON.Quaternion();
  89620. /**
  89621. * 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)
  89622. */
  89623. this.zDragFactor = 3;
  89624. /**
  89625. * If the behavior is currently in a dragging state
  89626. */
  89627. this.dragging = false;
  89628. /**
  89629. * 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)
  89630. */
  89631. this.dragDeltaRatio = 0.2;
  89632. /**
  89633. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89634. */
  89635. this.currentDraggingPointerID = -1;
  89636. /**
  89637. * If camera controls should be detached during the drag
  89638. */
  89639. this.detachCameraControls = true;
  89640. }
  89641. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89642. /**
  89643. * The name of the behavior
  89644. */
  89645. get: function () {
  89646. return "SixDofDrag";
  89647. },
  89648. enumerable: true,
  89649. configurable: true
  89650. });
  89651. /**
  89652. * Initializes the behavior
  89653. */
  89654. SixDofDragBehavior.prototype.init = function () { };
  89655. /**
  89656. * Attaches the scale behavior the passed in mesh
  89657. * @param ownerNode The mesh that will be scaled around once attached
  89658. */
  89659. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89660. var _this = this;
  89661. this._ownerNode = ownerNode;
  89662. this._scene = this._ownerNode.getScene();
  89663. if (!SixDofDragBehavior._virtualScene) {
  89664. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89665. this._scene.getEngine().scenes.pop();
  89666. }
  89667. var pickedMesh = null;
  89668. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89669. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89670. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89671. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89672. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89673. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89674. var pickPredicate = function (m) {
  89675. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89676. };
  89677. var attachedElement = null;
  89678. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89679. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89680. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89681. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89682. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89683. }
  89684. pickedMesh = _this._ownerNode;
  89685. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89686. // Set position and orientation of the controller
  89687. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89688. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89689. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89690. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89691. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89692. if (!pickedMesh.rotationQuaternion) {
  89693. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89694. }
  89695. var oldParent = pickedMesh.parent;
  89696. pickedMesh.setParent(null);
  89697. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89698. pickedMesh.setParent(oldParent);
  89699. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89700. // Update state
  89701. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89702. _this.dragging = true;
  89703. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89704. // Detatch camera controls
  89705. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89706. if (_this._scene.activeCamera.inputs.attachedElement) {
  89707. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  89708. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  89709. }
  89710. else {
  89711. attachedElement = null;
  89712. }
  89713. }
  89714. }
  89715. }
  89716. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89717. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89718. _this.dragging = false;
  89719. _this._moving = false;
  89720. _this.currentDraggingPointerID = -1;
  89721. pickedMesh = null;
  89722. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89723. // Reattach camera controls
  89724. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  89725. _this._scene.activeCamera.attachControl(attachedElement, true);
  89726. }
  89727. }
  89728. }
  89729. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89730. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89731. var zDragFactor = _this.zDragFactor;
  89732. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  89733. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  89734. zDragFactor = 0;
  89735. }
  89736. // Calculate controller drag distance in controller space
  89737. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89738. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89739. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  89740. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89741. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89742. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  89743. if (_this._virtualDragMesh.position.z < 0) {
  89744. _this._virtualDragMesh.position.z = 0;
  89745. }
  89746. // Update the controller position
  89747. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89748. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89749. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89750. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89751. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89752. if (pickedMesh.parent) {
  89753. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89754. }
  89755. if (!_this._moving) {
  89756. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89757. }
  89758. _this._moving = true;
  89759. }
  89760. }
  89761. });
  89762. var tmpQuaternion = new BABYLON.Quaternion();
  89763. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89764. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89765. if (_this.dragging && _this._moving && pickedMesh) {
  89766. // Slowly move mesh to avoid jitter
  89767. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89768. // Get change in rotation
  89769. tmpQuaternion.copyFrom(_this._startingOrientation);
  89770. tmpQuaternion.x = -tmpQuaternion.x;
  89771. tmpQuaternion.y = -tmpQuaternion.y;
  89772. tmpQuaternion.z = -tmpQuaternion.z;
  89773. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89774. // Convert change in rotation to only y axis rotation
  89775. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89776. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89777. // Slowly move mesh to avoid jitter
  89778. var oldParent = pickedMesh.parent;
  89779. pickedMesh.setParent(null);
  89780. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89781. pickedMesh.setParent(oldParent);
  89782. }
  89783. });
  89784. };
  89785. /**
  89786. * Detaches the behavior from the mesh
  89787. */
  89788. SixDofDragBehavior.prototype.detach = function () {
  89789. if (this._scene) {
  89790. this._scene.onPointerObservable.remove(this._pointerObserver);
  89791. }
  89792. if (this._ownerNode) {
  89793. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89794. }
  89795. if (this._virtualOriginMesh) {
  89796. this._virtualOriginMesh.dispose();
  89797. }
  89798. if (this._virtualDragMesh) {
  89799. this._virtualDragMesh.dispose();
  89800. }
  89801. };
  89802. return SixDofDragBehavior;
  89803. }());
  89804. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89805. })(BABYLON || (BABYLON = {}));
  89806. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89807. var BABYLON;
  89808. (function (BABYLON) {
  89809. /**
  89810. * @hidden
  89811. */
  89812. var FaceDirectionInfo = /** @class */ (function () {
  89813. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  89814. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  89815. if (diff === void 0) { diff = 0; }
  89816. if (ignore === void 0) { ignore = false; }
  89817. this.direction = direction;
  89818. this.rotatedDirection = rotatedDirection;
  89819. this.diff = diff;
  89820. this.ignore = ignore;
  89821. }
  89822. return FaceDirectionInfo;
  89823. }());
  89824. /**
  89825. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  89826. */
  89827. var AttachToBoxBehavior = /** @class */ (function () {
  89828. /**
  89829. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  89830. * @param ui The transform node that should be attched to the mesh
  89831. */
  89832. function AttachToBoxBehavior(ui) {
  89833. this.ui = ui;
  89834. /**
  89835. * The name of the behavior
  89836. */
  89837. this.name = "AttachToBoxBehavior";
  89838. /**
  89839. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  89840. */
  89841. this.distanceAwayFromFace = 0.15;
  89842. /**
  89843. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  89844. */
  89845. this.distanceAwayFromBottomOfFace = 0.15;
  89846. 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))];
  89847. this._tmpMatrix = new BABYLON.Matrix();
  89848. this._tmpVector = new BABYLON.Vector3();
  89849. this._zeroVector = BABYLON.Vector3.Zero();
  89850. this._lookAtTmpMatrix = new BABYLON.Matrix();
  89851. /* Does nothing */
  89852. }
  89853. /**
  89854. * Initializes the behavior
  89855. */
  89856. AttachToBoxBehavior.prototype.init = function () {
  89857. /* Does nothing */
  89858. };
  89859. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  89860. var _this = this;
  89861. // Go over each face and calculate the angle between the face's normal and targetDirection
  89862. this._faceVectors.forEach(function (v) {
  89863. if (!_this._target.rotationQuaternion) {
  89864. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  89865. }
  89866. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  89867. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  89868. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  89869. });
  89870. // Return the face information of the one with the normal closeset to target direction
  89871. return this._faceVectors.reduce(function (min, p) {
  89872. if (min.ignore) {
  89873. return p;
  89874. }
  89875. else if (p.ignore) {
  89876. return min;
  89877. }
  89878. else {
  89879. return min.diff < p.diff ? min : p;
  89880. }
  89881. }, this._faceVectors[0]);
  89882. };
  89883. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  89884. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  89885. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  89886. this._lookAtTmpMatrix.invert();
  89887. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  89888. };
  89889. /**
  89890. * Attaches the AttachToBoxBehavior to the passed in mesh
  89891. * @param target The mesh that the specified node will be attached to
  89892. */
  89893. AttachToBoxBehavior.prototype.attach = function (target) {
  89894. var _this = this;
  89895. this._target = target;
  89896. this._scene = this._target.getScene();
  89897. // Every frame, update the app bars position
  89898. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  89899. if (!_this._scene.activeCamera) {
  89900. return;
  89901. }
  89902. // Find the face closest to the cameras position
  89903. var cameraPos = _this._scene.activeCamera.position;
  89904. if (_this._scene.activeCamera.devicePosition) {
  89905. cameraPos = _this._scene.activeCamera.devicePosition;
  89906. }
  89907. var facing = _this._closestFace(cameraPos.subtract(target.position));
  89908. if (_this._scene.activeCamera.leftCamera) {
  89909. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89910. }
  89911. else {
  89912. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89913. }
  89914. // Get camera up direction
  89915. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  89916. // Ignore faces to not select a parrelel face for the up vector of the UI
  89917. _this._faceVectors.forEach(function (v) {
  89918. if (facing.direction.x && v.direction.x) {
  89919. v.ignore = true;
  89920. }
  89921. if (facing.direction.y && v.direction.y) {
  89922. v.ignore = true;
  89923. }
  89924. if (facing.direction.z && v.direction.z) {
  89925. v.ignore = true;
  89926. }
  89927. });
  89928. var facingUp = _this._closestFace(_this._tmpVector);
  89929. // Unignore faces
  89930. _this._faceVectors.forEach(function (v) {
  89931. v.ignore = false;
  89932. });
  89933. // Position the app bar on that face
  89934. _this.ui.position.copyFrom(target.position);
  89935. if (facing.direction.x) {
  89936. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89937. _this.ui.position.addInPlace(_this._tmpVector);
  89938. }
  89939. if (facing.direction.y) {
  89940. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89941. _this.ui.position.addInPlace(_this._tmpVector);
  89942. }
  89943. if (facing.direction.z) {
  89944. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  89945. _this.ui.position.addInPlace(_this._tmpVector);
  89946. }
  89947. // Rotate to be oriented properly to the camera
  89948. if (!_this.ui.rotationQuaternion) {
  89949. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  89950. }
  89951. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  89952. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  89953. // Place ui the correct distance from the bottom of the mesh
  89954. if (facingUp.direction.x) {
  89955. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  89956. }
  89957. if (facingUp.direction.y) {
  89958. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  89959. }
  89960. if (facingUp.direction.z) {
  89961. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  89962. }
  89963. _this.ui.position.addInPlace(_this._tmpVector);
  89964. });
  89965. };
  89966. /**
  89967. * Detaches the behavior from the mesh
  89968. */
  89969. AttachToBoxBehavior.prototype.detach = function () {
  89970. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  89971. };
  89972. return AttachToBoxBehavior;
  89973. }());
  89974. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  89975. })(BABYLON || (BABYLON = {}));
  89976. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  89977. var BABYLON;
  89978. (function (BABYLON) {
  89979. /**
  89980. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89981. */
  89982. var Gizmo = /** @class */ (function () {
  89983. /**
  89984. * Creates a gizmo
  89985. * @param gizmoLayer The utility layer the gizmo will be added to
  89986. */
  89987. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89988. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89989. var _this = this;
  89990. this.gizmoLayer = gizmoLayer;
  89991. this._scaleFactor = 3;
  89992. this._tmpMatrix = new BABYLON.Matrix();
  89993. /**
  89994. * If a custom mesh has been set (Default: false)
  89995. */
  89996. this._customMeshSet = false;
  89997. /**
  89998. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89999. */
  90000. this.updateGizmoRotationToMatchAttachedMesh = true;
  90001. /**
  90002. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  90003. */
  90004. this.updateGizmoPositionToMatchAttachedMesh = true;
  90005. /**
  90006. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  90007. */
  90008. this._updateScale = true;
  90009. this._interactionsEnabled = true;
  90010. this._tempVector = new BABYLON.Vector3();
  90011. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  90012. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  90013. _this._update();
  90014. });
  90015. this.attachedMesh = null;
  90016. }
  90017. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  90018. /**
  90019. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  90020. * * When set, interactions will be enabled
  90021. */
  90022. get: function () {
  90023. return this._attachedMesh;
  90024. },
  90025. set: function (value) {
  90026. this._attachedMesh = value;
  90027. this._rootMesh.setEnabled(value ? true : false);
  90028. this._attachedMeshChanged(value);
  90029. },
  90030. enumerable: true,
  90031. configurable: true
  90032. });
  90033. /**
  90034. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  90035. * @param mesh The mesh to replace the default mesh of the gizmo
  90036. */
  90037. Gizmo.prototype.setCustomMesh = function (mesh) {
  90038. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  90039. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  90040. }
  90041. this._rootMesh.getChildMeshes().forEach(function (c) {
  90042. c.dispose();
  90043. });
  90044. mesh.parent = this._rootMesh;
  90045. this._customMeshSet = true;
  90046. };
  90047. Gizmo.prototype._attachedMeshChanged = function (value) {
  90048. };
  90049. /**
  90050. * @hidden
  90051. * Updates the gizmo to match the attached mesh's position/rotation
  90052. */
  90053. Gizmo.prototype._update = function () {
  90054. if (this.attachedMesh) {
  90055. if (this.updateGizmoRotationToMatchAttachedMesh) {
  90056. if (!this._rootMesh.rotationQuaternion) {
  90057. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  90058. }
  90059. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  90060. this._tempVector.copyFrom(this.attachedMesh.scaling);
  90061. if (this.attachedMesh.scaling.x < 0) {
  90062. this.attachedMesh.scaling.x *= -1;
  90063. }
  90064. if (this.attachedMesh.scaling.y < 0) {
  90065. this.attachedMesh.scaling.y *= -1;
  90066. }
  90067. if (this.attachedMesh.scaling.z < 0) {
  90068. this.attachedMesh.scaling.z *= -1;
  90069. }
  90070. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  90071. this.attachedMesh.scaling.copyFrom(this._tempVector);
  90072. this.attachedMesh.computeWorldMatrix();
  90073. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  90074. }
  90075. if (this.updateGizmoPositionToMatchAttachedMesh) {
  90076. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  90077. }
  90078. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  90079. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  90080. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  90081. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  90082. }
  90083. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  90084. var dist = this._tempVector.length() / this._scaleFactor;
  90085. this._rootMesh.scaling.set(dist, dist, dist);
  90086. }
  90087. }
  90088. };
  90089. /**
  90090. * Disposes of the gizmo
  90091. */
  90092. Gizmo.prototype.dispose = function () {
  90093. this._rootMesh.dispose();
  90094. if (this._beforeRenderObserver) {
  90095. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90096. }
  90097. };
  90098. return Gizmo;
  90099. }());
  90100. BABYLON.Gizmo = Gizmo;
  90101. })(BABYLON || (BABYLON = {}));
  90102. //# sourceMappingURL=babylon.gizmo.js.map
  90103. var BABYLON;
  90104. (function (BABYLON) {
  90105. /**
  90106. * Single axis drag gizmo
  90107. */
  90108. var AxisDragGizmo = /** @class */ (function (_super) {
  90109. __extends(AxisDragGizmo, _super);
  90110. /**
  90111. * Creates an AxisDragGizmo
  90112. * @param gizmoLayer The utility layer the gizmo will be added to
  90113. * @param dragAxis The axis which the gizmo will be able to drag on
  90114. * @param color The color of the gizmo
  90115. */
  90116. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  90117. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90118. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90119. var _this = _super.call(this, gizmoLayer) || this;
  90120. _this._pointerObserver = null;
  90121. /**
  90122. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90123. */
  90124. _this.snapDistance = 0;
  90125. /**
  90126. * Event that fires each time the gizmo snaps to a new location.
  90127. * * snapDistance is the the change in distance
  90128. */
  90129. _this.onSnapObservable = new BABYLON.Observable();
  90130. // Create Material
  90131. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90132. coloredMaterial.disableLighting = true;
  90133. coloredMaterial.emissiveColor = color;
  90134. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90135. hoverMaterial.disableLighting = true;
  90136. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90137. // Build mesh on root node
  90138. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90139. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  90140. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90141. arrowTail.color = coloredMaterial.emissiveColor;
  90142. arrow.addChild(arrowMesh);
  90143. arrow.addChild(arrowTail);
  90144. // Position arrow pointing in its drag axis
  90145. arrowMesh.scaling.scaleInPlace(0.05);
  90146. arrowMesh.material = coloredMaterial;
  90147. arrowMesh.rotation.x = Math.PI / 2;
  90148. arrowMesh.position.z += 0.3;
  90149. arrowTail.scaling.scaleInPlace(0.2);
  90150. arrowTail.rotation.x = Math.PI / 2;
  90151. arrowTail.material = coloredMaterial;
  90152. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90153. _this._rootMesh.addChild(arrow);
  90154. var currentSnapDragDistance = 0;
  90155. var tmpVector = new BABYLON.Vector3();
  90156. var tmpSnapEvent = { snapDistance: 0 };
  90157. // Add drag behavior to handle events when the gizmo is dragged
  90158. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90159. _this.dragBehavior.moveAttached = false;
  90160. _this._rootMesh.addBehavior(_this.dragBehavior);
  90161. _this.dragBehavior.onDragObservable.add(function (event) {
  90162. if (_this.attachedMesh) {
  90163. // Snapping logic
  90164. if (_this.snapDistance == 0) {
  90165. _this.attachedMesh.position.addInPlace(event.delta);
  90166. }
  90167. else {
  90168. currentSnapDragDistance += event.dragDistance;
  90169. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90170. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  90171. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90172. event.delta.normalizeToRef(tmpVector);
  90173. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  90174. _this.attachedMesh.position.addInPlace(tmpVector);
  90175. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90176. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90177. }
  90178. }
  90179. }
  90180. });
  90181. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90182. if (_this._customMeshSet) {
  90183. return;
  90184. }
  90185. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90186. var material = isHovered ? hoverMaterial : coloredMaterial;
  90187. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90188. m.material = material;
  90189. if (m.color) {
  90190. m.color = material.emissiveColor;
  90191. }
  90192. });
  90193. });
  90194. return _this;
  90195. }
  90196. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  90197. if (this.dragBehavior) {
  90198. this.dragBehavior.enabled = value ? true : false;
  90199. }
  90200. };
  90201. /**
  90202. * Disposes of the gizmo
  90203. */
  90204. AxisDragGizmo.prototype.dispose = function () {
  90205. this.onSnapObservable.clear();
  90206. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90207. this.dragBehavior.detach();
  90208. _super.prototype.dispose.call(this);
  90209. };
  90210. return AxisDragGizmo;
  90211. }(BABYLON.Gizmo));
  90212. BABYLON.AxisDragGizmo = AxisDragGizmo;
  90213. })(BABYLON || (BABYLON = {}));
  90214. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  90215. var BABYLON;
  90216. (function (BABYLON) {
  90217. /**
  90218. * Single axis scale gizmo
  90219. */
  90220. var AxisScaleGizmo = /** @class */ (function (_super) {
  90221. __extends(AxisScaleGizmo, _super);
  90222. /**
  90223. * Creates an AxisScaleGizmo
  90224. * @param gizmoLayer The utility layer the gizmo will be added to
  90225. * @param dragAxis The axis which the gizmo will be able to scale on
  90226. * @param color The color of the gizmo
  90227. */
  90228. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  90229. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90230. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90231. var _this = _super.call(this, gizmoLayer) || this;
  90232. _this._pointerObserver = null;
  90233. /**
  90234. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  90235. */
  90236. _this.snapDistance = 0;
  90237. /**
  90238. * Event that fires each time the gizmo snaps to a new location.
  90239. * * snapDistance is the the change in distance
  90240. */
  90241. _this.onSnapObservable = new BABYLON.Observable();
  90242. // Create Material
  90243. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90244. coloredMaterial.disableLighting = true;
  90245. coloredMaterial.emissiveColor = color;
  90246. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90247. hoverMaterial.disableLighting = true;
  90248. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90249. // Build mesh on root node
  90250. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90251. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  90252. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.5, 0)] }, gizmoLayer.utilityLayerScene);
  90253. arrowTail.color = coloredMaterial.emissiveColor;
  90254. arrow.addChild(arrowMesh);
  90255. arrow.addChild(arrowTail);
  90256. // Position arrow pointing in its drag axis
  90257. arrowMesh.scaling.scaleInPlace(0.1);
  90258. arrowMesh.material = coloredMaterial;
  90259. arrowMesh.rotation.x = Math.PI / 2;
  90260. arrowMesh.position.z += 0.3;
  90261. arrowTail.scaling.scaleInPlace(0.2);
  90262. arrowTail.rotation.x = Math.PI / 2;
  90263. arrowTail.material = coloredMaterial;
  90264. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  90265. _this._rootMesh.addChild(arrow);
  90266. // Add drag behavior to handle events when the gizmo is dragged
  90267. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90268. _this.dragBehavior.moveAttached = false;
  90269. _this._rootMesh.addBehavior(_this.dragBehavior);
  90270. var currentSnapDragDistance = 0;
  90271. var tmpVector = new BABYLON.Vector3();
  90272. var tmpSnapEvent = { snapDistance: 0 };
  90273. _this.dragBehavior.onDragObservable.add(function (event) {
  90274. if (_this.attachedMesh) {
  90275. // Snapping logic
  90276. var snapped = false;
  90277. var dragSteps = 0;
  90278. if (_this.snapDistance == 0) {
  90279. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  90280. }
  90281. else {
  90282. currentSnapDragDistance += event.dragDistance;
  90283. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90284. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90285. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90286. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  90287. snapped = true;
  90288. }
  90289. else {
  90290. tmpVector.scaleInPlace(0);
  90291. }
  90292. }
  90293. _this.attachedMesh.scaling.addInPlace(tmpVector);
  90294. if (snapped) {
  90295. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  90296. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90297. }
  90298. }
  90299. });
  90300. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90301. if (_this._customMeshSet) {
  90302. return;
  90303. }
  90304. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90305. var material = isHovered ? hoverMaterial : coloredMaterial;
  90306. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90307. m.material = material;
  90308. if (m.color) {
  90309. m.color = material.emissiveColor;
  90310. }
  90311. });
  90312. });
  90313. return _this;
  90314. }
  90315. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  90316. if (this.dragBehavior) {
  90317. this.dragBehavior.enabled = value ? true : false;
  90318. }
  90319. };
  90320. /**
  90321. * Disposes of the gizmo
  90322. */
  90323. AxisScaleGizmo.prototype.dispose = function () {
  90324. this.onSnapObservable.clear();
  90325. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90326. this.dragBehavior.detach();
  90327. _super.prototype.dispose.call(this);
  90328. };
  90329. return AxisScaleGizmo;
  90330. }(BABYLON.Gizmo));
  90331. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  90332. })(BABYLON || (BABYLON = {}));
  90333. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  90334. var BABYLON;
  90335. (function (BABYLON) {
  90336. /**
  90337. * Single plane rotation gizmo
  90338. */
  90339. var PlaneRotationGizmo = /** @class */ (function (_super) {
  90340. __extends(PlaneRotationGizmo, _super);
  90341. /**
  90342. * Creates a PlaneRotationGizmo
  90343. * @param gizmoLayer The utility layer the gizmo will be added to
  90344. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  90345. * @param color The color of the gizmo
  90346. */
  90347. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  90348. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90349. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90350. var _this = _super.call(this, gizmoLayer) || this;
  90351. _this._pointerObserver = null;
  90352. /**
  90353. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  90354. */
  90355. _this.snapDistance = 0;
  90356. /**
  90357. * Event that fires each time the gizmo snaps to a new location.
  90358. * * snapDistance is the the change in distance
  90359. */
  90360. _this.onSnapObservable = new BABYLON.Observable();
  90361. // Create Material
  90362. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90363. coloredMaterial.disableLighting = true;
  90364. coloredMaterial.emissiveColor = color;
  90365. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90366. hoverMaterial.disableLighting = true;
  90367. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90368. // Build mesh on root node
  90369. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90370. // Create circle out of lines
  90371. var tessellation = 20;
  90372. var radius = 2;
  90373. var points = new Array();
  90374. for (var i = 0; i < tessellation; i++) {
  90375. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  90376. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  90377. }
  90378. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  90379. rotationMesh.color = coloredMaterial.emissiveColor;
  90380. // Position arrow pointing in its drag axis
  90381. rotationMesh.scaling.scaleInPlace(0.1);
  90382. rotationMesh.material = coloredMaterial;
  90383. rotationMesh.rotation.x = Math.PI / 2;
  90384. parentMesh.addChild(rotationMesh);
  90385. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  90386. _this._rootMesh.addChild(parentMesh);
  90387. // Add drag behavior to handle events when the gizmo is dragged
  90388. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  90389. _this.dragBehavior.moveAttached = false;
  90390. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  90391. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  90392. _this._rootMesh.addBehavior(_this.dragBehavior);
  90393. var lastDragPosition = new BABYLON.Vector3();
  90394. _this.dragBehavior.onDragStartObservable.add(function (e) {
  90395. if (_this.attachedMesh) {
  90396. lastDragPosition.copyFrom(e.dragPlanePoint);
  90397. }
  90398. });
  90399. var rotationMatrix = new BABYLON.Matrix();
  90400. var planeNormalTowardsCamera = new BABYLON.Vector3();
  90401. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  90402. var tmpSnapEvent = { snapDistance: 0 };
  90403. var currentSnapDragDistance = 0;
  90404. _this.dragBehavior.onDragObservable.add(function (event) {
  90405. if (_this.attachedMesh) {
  90406. if (!_this.attachedMesh.rotationQuaternion) {
  90407. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90408. }
  90409. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  90410. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  90411. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  90412. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  90413. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  90414. var angle = Math.atan2(cross.length(), dot);
  90415. planeNormalTowardsCamera.copyFrom(planeNormal);
  90416. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  90417. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90418. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  90419. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  90420. }
  90421. // Flip up vector depending on which side the camera is on
  90422. if (gizmoLayer.utilityLayerScene.activeCamera) {
  90423. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  90424. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  90425. planeNormalTowardsCamera.scaleInPlace(-1);
  90426. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  90427. }
  90428. }
  90429. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  90430. if (halfCircleSide)
  90431. angle = -angle;
  90432. // Snapping logic
  90433. var snapped = false;
  90434. if (_this.snapDistance != 0) {
  90435. currentSnapDragDistance += angle;
  90436. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  90437. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  90438. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  90439. angle = _this.snapDistance * dragSteps;
  90440. snapped = true;
  90441. }
  90442. else {
  90443. angle = 0;
  90444. }
  90445. }
  90446. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  90447. var quaternionCoefficient = Math.sin(angle / 2);
  90448. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  90449. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  90450. // Rotate selected mesh quaternion over fixed axis
  90451. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  90452. }
  90453. else {
  90454. // Rotate selected mesh quaternion over rotated axis
  90455. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  90456. }
  90457. lastDragPosition.copyFrom(event.dragPlanePoint);
  90458. if (snapped) {
  90459. tmpSnapEvent.snapDistance = angle;
  90460. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  90461. }
  90462. }
  90463. });
  90464. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90465. if (_this._customMeshSet) {
  90466. return;
  90467. }
  90468. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  90469. var material = isHovered ? hoverMaterial : coloredMaterial;
  90470. _this._rootMesh.getChildMeshes().forEach(function (m) {
  90471. m.material = material;
  90472. if (m.color) {
  90473. m.color = material.emissiveColor;
  90474. }
  90475. });
  90476. });
  90477. return _this;
  90478. }
  90479. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  90480. if (this.dragBehavior) {
  90481. this.dragBehavior.enabled = value ? true : false;
  90482. }
  90483. };
  90484. /**
  90485. * Disposes of the gizmo
  90486. */
  90487. PlaneRotationGizmo.prototype.dispose = function () {
  90488. this.onSnapObservable.clear();
  90489. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90490. this.dragBehavior.detach();
  90491. _super.prototype.dispose.call(this);
  90492. };
  90493. return PlaneRotationGizmo;
  90494. }(BABYLON.Gizmo));
  90495. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  90496. })(BABYLON || (BABYLON = {}));
  90497. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  90498. var BABYLON;
  90499. (function (BABYLON) {
  90500. /**
  90501. * Gizmo that enables dragging a mesh along 3 axis
  90502. */
  90503. var PositionGizmo = /** @class */ (function (_super) {
  90504. __extends(PositionGizmo, _super);
  90505. /**
  90506. * Creates a PositionGizmo
  90507. * @param gizmoLayer The utility layer the gizmo will be added to
  90508. */
  90509. function PositionGizmo(gizmoLayer) {
  90510. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90511. var _this = _super.call(this, gizmoLayer) || this;
  90512. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90513. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90514. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90515. _this.attachedMesh = null;
  90516. return _this;
  90517. }
  90518. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  90519. set: function (mesh) {
  90520. if (this.xGizmo) {
  90521. this.xGizmo.attachedMesh = mesh;
  90522. this.yGizmo.attachedMesh = mesh;
  90523. this.zGizmo.attachedMesh = mesh;
  90524. }
  90525. },
  90526. enumerable: true,
  90527. configurable: true
  90528. });
  90529. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90530. get: function () {
  90531. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90532. },
  90533. set: function (value) {
  90534. if (this.xGizmo) {
  90535. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90536. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90537. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90538. }
  90539. },
  90540. enumerable: true,
  90541. configurable: true
  90542. });
  90543. /**
  90544. * Disposes of the gizmo
  90545. */
  90546. PositionGizmo.prototype.dispose = function () {
  90547. this.xGizmo.dispose();
  90548. this.yGizmo.dispose();
  90549. this.zGizmo.dispose();
  90550. };
  90551. /**
  90552. * CustomMeshes are not supported by this gizmo
  90553. * @param mesh The mesh to replace the default mesh of the gizmo
  90554. */
  90555. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  90556. 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)");
  90557. };
  90558. return PositionGizmo;
  90559. }(BABYLON.Gizmo));
  90560. BABYLON.PositionGizmo = PositionGizmo;
  90561. })(BABYLON || (BABYLON = {}));
  90562. //# sourceMappingURL=babylon.positionGizmo.js.map
  90563. var BABYLON;
  90564. (function (BABYLON) {
  90565. /**
  90566. * Gizmo that enables rotating a mesh along 3 axis
  90567. */
  90568. var RotationGizmo = /** @class */ (function (_super) {
  90569. __extends(RotationGizmo, _super);
  90570. /**
  90571. * Creates a RotationGizmo
  90572. * @param gizmoLayer The utility layer the gizmo will be added to
  90573. */
  90574. function RotationGizmo(gizmoLayer) {
  90575. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90576. var _this = _super.call(this, gizmoLayer) || this;
  90577. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90578. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90579. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90580. _this.attachedMesh = null;
  90581. return _this;
  90582. }
  90583. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90584. set: function (mesh) {
  90585. if (this.xGizmo) {
  90586. this.xGizmo.attachedMesh = mesh;
  90587. this.yGizmo.attachedMesh = mesh;
  90588. this.zGizmo.attachedMesh = mesh;
  90589. }
  90590. },
  90591. enumerable: true,
  90592. configurable: true
  90593. });
  90594. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90595. get: function () {
  90596. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90597. },
  90598. set: function (value) {
  90599. if (this.xGizmo) {
  90600. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90601. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90602. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90603. }
  90604. },
  90605. enumerable: true,
  90606. configurable: true
  90607. });
  90608. /**
  90609. * Disposes of the gizmo
  90610. */
  90611. RotationGizmo.prototype.dispose = function () {
  90612. this.xGizmo.dispose();
  90613. this.yGizmo.dispose();
  90614. this.zGizmo.dispose();
  90615. };
  90616. /**
  90617. * CustomMeshes are not supported by this gizmo
  90618. * @param mesh The mesh to replace the default mesh of the gizmo
  90619. */
  90620. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  90621. 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)");
  90622. };
  90623. return RotationGizmo;
  90624. }(BABYLON.Gizmo));
  90625. BABYLON.RotationGizmo = RotationGizmo;
  90626. })(BABYLON || (BABYLON = {}));
  90627. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90628. var BABYLON;
  90629. (function (BABYLON) {
  90630. /**
  90631. * Gizmo that enables scaling a mesh along 3 axis
  90632. */
  90633. var ScaleGizmo = /** @class */ (function (_super) {
  90634. __extends(ScaleGizmo, _super);
  90635. /**
  90636. * Creates a ScaleGizmo
  90637. * @param gizmoLayer The utility layer the gizmo will be added to
  90638. */
  90639. function ScaleGizmo(gizmoLayer) {
  90640. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90641. var _this = _super.call(this, gizmoLayer) || this;
  90642. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90643. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90644. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90645. _this.attachedMesh = null;
  90646. return _this;
  90647. }
  90648. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90649. set: function (mesh) {
  90650. if (this.xGizmo) {
  90651. this.xGizmo.attachedMesh = mesh;
  90652. this.yGizmo.attachedMesh = mesh;
  90653. this.zGizmo.attachedMesh = mesh;
  90654. }
  90655. },
  90656. enumerable: true,
  90657. configurable: true
  90658. });
  90659. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90660. get: function () {
  90661. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90662. },
  90663. set: function (value) {
  90664. if (this.xGizmo) {
  90665. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90666. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90667. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90668. }
  90669. },
  90670. enumerable: true,
  90671. configurable: true
  90672. });
  90673. /**
  90674. * Disposes of the gizmo
  90675. */
  90676. ScaleGizmo.prototype.dispose = function () {
  90677. this.xGizmo.dispose();
  90678. this.yGizmo.dispose();
  90679. this.zGizmo.dispose();
  90680. };
  90681. return ScaleGizmo;
  90682. }(BABYLON.Gizmo));
  90683. BABYLON.ScaleGizmo = ScaleGizmo;
  90684. })(BABYLON || (BABYLON = {}));
  90685. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90686. var BABYLON;
  90687. (function (BABYLON) {
  90688. /**
  90689. * Bounding box gizmo
  90690. */
  90691. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90692. __extends(BoundingBoxGizmo, _super);
  90693. /**
  90694. * Creates an BoundingBoxGizmo
  90695. * @param gizmoLayer The utility layer the gizmo will be added to
  90696. * @param color The color of the gizmo
  90697. */
  90698. function BoundingBoxGizmo(color, gizmoLayer) {
  90699. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90700. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  90701. var _this = _super.call(this, gizmoLayer) || this;
  90702. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90703. _this._renderObserver = null;
  90704. _this._pointerObserver = null;
  90705. _this._scaleDragSpeed = 0.2;
  90706. _this._tmpQuaternion = new BABYLON.Quaternion();
  90707. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90708. /**
  90709. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90710. */
  90711. _this.rotationSphereSize = 0.1;
  90712. /**
  90713. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90714. */
  90715. _this.scaleBoxSize = 0.1;
  90716. /**
  90717. * 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)
  90718. */
  90719. _this.fixedDragMeshScreenSize = false;
  90720. /**
  90721. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90722. */
  90723. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90724. /**
  90725. * Fired when a rotation sphere or scale box is dragged
  90726. */
  90727. _this.onDragStartObservable = new BABYLON.Observable();
  90728. /**
  90729. * Fired when a rotation sphere or scale box drag is started
  90730. */
  90731. _this.onDragObservable = new BABYLON.Observable();
  90732. /**
  90733. * Fired when a rotation sphere or scale box drag is needed
  90734. */
  90735. _this.onDragEndObservable = new BABYLON.Observable();
  90736. _this._existingMeshScale = new BABYLON.Vector3();
  90737. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90738. _this._updateScale = false;
  90739. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  90740. // Create Materials
  90741. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90742. coloredMaterial.disableLighting = true;
  90743. coloredMaterial.emissiveColor = color;
  90744. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90745. hoverColoredMaterial.disableLighting = true;
  90746. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90747. // Build bounding box out of lines
  90748. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90749. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90750. var lines = [];
  90751. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90752. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90753. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90754. 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));
  90755. 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));
  90756. 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));
  90757. 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));
  90758. 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));
  90759. 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));
  90760. 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));
  90761. 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));
  90762. 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));
  90763. lines.forEach(function (l) {
  90764. l.color = color;
  90765. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90766. l.isPickable = false;
  90767. _this._lineBoundingBox.addChild(l);
  90768. });
  90769. _this._rootMesh.addChild(_this._lineBoundingBox);
  90770. // Create rotation spheres
  90771. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90772. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90773. var _loop_1 = function (i_1) {
  90774. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90775. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90776. sphere.material = coloredMaterial;
  90777. // Drag behavior
  90778. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90779. _dragBehavior.moveAttached = false;
  90780. _dragBehavior.updateDragPlane = false;
  90781. sphere.addBehavior(_dragBehavior);
  90782. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90783. var totalTurnAmountOfDrag = 0;
  90784. _dragBehavior.onDragStartObservable.add(function (event) {
  90785. startingTurnDirection.copyFrom(sphere.forward);
  90786. totalTurnAmountOfDrag = 0;
  90787. });
  90788. _dragBehavior.onDragObservable.add(function (event) {
  90789. _this.onDragObservable.notifyObservers({});
  90790. if (_this.attachedMesh) {
  90791. var worldDragDirection = startingTurnDirection;
  90792. // Project the world right on to the drag plane
  90793. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90794. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90795. // project drag delta on to the resulting drag axis and rotate based on that
  90796. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90797. // Make rotation relative to size of mesh.
  90798. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  90799. // Rotate based on axis
  90800. if (!_this.attachedMesh.rotationQuaternion) {
  90801. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90802. }
  90803. if (!_this._anchorMesh.rotationQuaternion) {
  90804. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  90805. }
  90806. // Do not allow the object to turn more than a full circle
  90807. totalTurnAmountOfDrag += projectDist;
  90808. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90809. if (i_1 >= 8) {
  90810. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90811. }
  90812. else if (i_1 >= 4) {
  90813. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90814. }
  90815. else {
  90816. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90817. }
  90818. // Rotate around center of bounding box
  90819. _this._anchorMesh.addChild(_this.attachedMesh);
  90820. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  90821. _this._anchorMesh.removeChild(_this.attachedMesh);
  90822. }
  90823. _this.updateBoundingBox();
  90824. }
  90825. });
  90826. // Selection/deselection
  90827. _dragBehavior.onDragStartObservable.add(function () {
  90828. _this.onDragStartObservable.notifyObservers({});
  90829. _this._selectNode(sphere);
  90830. });
  90831. _dragBehavior.onDragEndObservable.add(function () {
  90832. _this.onDragEndObservable.notifyObservers({});
  90833. _this._selectNode(null);
  90834. });
  90835. this_1._rotateSpheresParent.addChild(sphere);
  90836. };
  90837. var this_1 = this, _dragBehavior;
  90838. for (var i_1 = 0; i_1 < 12; i_1++) {
  90839. _loop_1(i_1);
  90840. }
  90841. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90842. // Create scale cubes
  90843. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90844. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90845. for (var i = 0; i < 2; i++) {
  90846. for (var j = 0; j < 2; j++) {
  90847. var _loop_2 = function () {
  90848. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90849. box.material = coloredMaterial;
  90850. // Dragging logic
  90851. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90852. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90853. _dragBehavior.moveAttached = false;
  90854. box.addBehavior(_dragBehavior);
  90855. _dragBehavior.onDragObservable.add(function (event) {
  90856. _this.onDragObservable.notifyObservers({});
  90857. if (_this.attachedMesh) {
  90858. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  90859. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  90860. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90861. _this.updateBoundingBox();
  90862. // Scale from the position of the opposite corner
  90863. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  90864. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  90865. _this._anchorMesh.addChild(_this.attachedMesh);
  90866. _this._anchorMesh.scaling.addInPlace(deltaScale);
  90867. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  90868. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  90869. }
  90870. _this._anchorMesh.removeChild(_this.attachedMesh);
  90871. }
  90872. });
  90873. // Selection/deselection
  90874. _dragBehavior.onDragStartObservable.add(function () {
  90875. _this.onDragStartObservable.notifyObservers({});
  90876. _this._selectNode(box);
  90877. });
  90878. _dragBehavior.onDragEndObservable.add(function () {
  90879. _this.onDragEndObservable.notifyObservers({});
  90880. _this._selectNode(null);
  90881. });
  90882. this_2._scaleBoxesParent.addChild(box);
  90883. };
  90884. var this_2 = this, _dragBehavior;
  90885. for (var k = 0; k < 2; k++) {
  90886. _loop_2();
  90887. }
  90888. }
  90889. }
  90890. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90891. // Hover color change
  90892. var pointerIds = new Array();
  90893. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90894. if (!pointerIds[pointerInfo.event.pointerId]) {
  90895. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90896. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90897. pointerIds[pointerInfo.event.pointerId] = mesh;
  90898. mesh.material = hoverColoredMaterial;
  90899. }
  90900. });
  90901. }
  90902. else {
  90903. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90904. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90905. delete pointerIds[pointerInfo.event.pointerId];
  90906. }
  90907. }
  90908. });
  90909. // Update bounding box positions
  90910. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90911. // Only update the bouding box if scaling has changed
  90912. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  90913. _this.updateBoundingBox();
  90914. }
  90915. });
  90916. _this.updateBoundingBox();
  90917. return _this;
  90918. }
  90919. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  90920. if (value) {
  90921. // Reset anchor mesh to match attached mesh's scale
  90922. // This is needed to avoid invalid box/sphere position on first drag
  90923. this._anchorMesh.addChild(value);
  90924. this._anchorMesh.removeChild(value);
  90925. this.updateBoundingBox();
  90926. }
  90927. };
  90928. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90929. this._rotateSpheresParent.getChildMeshes()
  90930. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90931. m.isVisible = (!selectedMesh || m == selectedMesh);
  90932. });
  90933. };
  90934. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  90935. var _this = this;
  90936. mesh.computeWorldMatrix(true);
  90937. mesh.getChildMeshes().forEach(function (m) {
  90938. _this._recurseComputeWorld(m);
  90939. });
  90940. };
  90941. /**
  90942. * Updates the bounding box information for the Gizmo
  90943. */
  90944. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  90945. this._update();
  90946. if (this.attachedMesh) {
  90947. // Rotate based on axis
  90948. if (!this.attachedMesh.rotationQuaternion) {
  90949. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  90950. }
  90951. if (!this._anchorMesh.rotationQuaternion) {
  90952. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  90953. }
  90954. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90955. // Store original position and reset mesh to origin before computing the bounding box
  90956. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  90957. this._tmpVector.copyFrom(this.attachedMesh.position);
  90958. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  90959. this.attachedMesh.position.set(0, 0, 0);
  90960. // Update bounding dimensions/positions
  90961. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors();
  90962. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  90963. // Update gizmo to match bounding box scaling and rotation
  90964. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90965. 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);
  90966. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  90967. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  90968. this._lineBoundingBox.computeWorldMatrix();
  90969. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  90970. // restore position/rotation values
  90971. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  90972. this.attachedMesh.position.copyFrom(this._tmpVector);
  90973. this._recurseComputeWorld(this.attachedMesh);
  90974. }
  90975. // Update rotation sphere locations
  90976. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90977. for (var i = 0; i < 3; i++) {
  90978. for (var j = 0; j < 2; j++) {
  90979. for (var k = 0; k < 2; k++) {
  90980. var index = ((i * 4) + (j * 2)) + k;
  90981. if (i == 0) {
  90982. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90983. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90984. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90985. }
  90986. if (i == 1) {
  90987. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90988. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90989. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90990. }
  90991. if (i == 2) {
  90992. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90993. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90994. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90995. }
  90996. if (this.fixedDragMeshScreenSize) {
  90997. this._rootMesh.computeWorldMatrix();
  90998. this._rotateSpheresParent.computeWorldMatrix();
  90999. rotateSpheres[index].computeWorldMatrix();
  91000. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91001. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91002. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91003. }
  91004. else {
  91005. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  91006. }
  91007. }
  91008. }
  91009. }
  91010. // Update scale box locations
  91011. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  91012. for (var i = 0; i < 2; i++) {
  91013. for (var j = 0; j < 2; j++) {
  91014. for (var k = 0; k < 2; k++) {
  91015. var index = ((i * 4) + (j * 2)) + k;
  91016. if (scaleBoxes[index]) {
  91017. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  91018. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  91019. if (this.fixedDragMeshScreenSize) {
  91020. this._rootMesh.computeWorldMatrix();
  91021. this._scaleBoxesParent.computeWorldMatrix();
  91022. scaleBoxes[index].computeWorldMatrix();
  91023. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  91024. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  91025. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  91026. }
  91027. else {
  91028. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  91029. }
  91030. }
  91031. }
  91032. }
  91033. }
  91034. if (this.attachedMesh) {
  91035. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  91036. }
  91037. };
  91038. /**
  91039. * Enables rotation on the specified axis and disables rotation on the others
  91040. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  91041. */
  91042. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  91043. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  91044. if (i < 4) {
  91045. m.setEnabled(axis.indexOf("x") != -1);
  91046. }
  91047. else if (i < 8) {
  91048. m.setEnabled(axis.indexOf("y") != -1);
  91049. }
  91050. else {
  91051. m.setEnabled(axis.indexOf("z") != -1);
  91052. }
  91053. });
  91054. };
  91055. /**
  91056. * Disposes of the gizmo
  91057. */
  91058. BoundingBoxGizmo.prototype.dispose = function () {
  91059. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91060. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  91061. this._lineBoundingBox.dispose();
  91062. this._rotateSpheresParent.dispose();
  91063. this._scaleBoxesParent.dispose();
  91064. _super.prototype.dispose.call(this);
  91065. };
  91066. /**
  91067. * 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)
  91068. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  91069. * @returns the bounding box mesh with the passed in mesh as a child
  91070. */
  91071. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  91072. var makeNotPickable = function (root) {
  91073. root.isPickable = false;
  91074. root.getChildMeshes().forEach(function (c) {
  91075. makeNotPickable(c);
  91076. });
  91077. };
  91078. makeNotPickable(mesh);
  91079. // Reset position to get boudning box from origin with no rotation
  91080. if (!mesh.rotationQuaternion) {
  91081. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  91082. }
  91083. var oldPos = mesh.position.clone();
  91084. var oldRot = mesh.rotationQuaternion.clone();
  91085. mesh.rotationQuaternion.set(0, 0, 0, 1);
  91086. mesh.position.set(0, 0, 0);
  91087. // Update bounding dimensions/positions
  91088. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  91089. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  91090. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  91091. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  91092. // Restore original positions
  91093. mesh.addChild(box);
  91094. mesh.rotationQuaternion.copyFrom(oldRot);
  91095. mesh.position.copyFrom(oldPos);
  91096. // Reverse parenting
  91097. mesh.removeChild(box);
  91098. box.addChild(mesh);
  91099. box.visibility = 0;
  91100. return box;
  91101. };
  91102. /**
  91103. * CustomMeshes are not supported by this gizmo
  91104. * @param mesh The mesh to replace the default mesh of the gizmo
  91105. */
  91106. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  91107. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  91108. };
  91109. return BoundingBoxGizmo;
  91110. }(BABYLON.Gizmo));
  91111. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  91112. })(BABYLON || (BABYLON = {}));
  91113. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  91114. var BABYLON;
  91115. (function (BABYLON) {
  91116. /**
  91117. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  91118. */
  91119. var GizmoManager = /** @class */ (function () {
  91120. /**
  91121. * Instatiates a gizmo manager
  91122. * @param scene the scene to overlay the gizmos on top of
  91123. */
  91124. function GizmoManager(scene) {
  91125. var _this = this;
  91126. this.scene = scene;
  91127. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  91128. this._pointerObserver = null;
  91129. this._attachedMesh = null;
  91130. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  91131. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  91132. /**
  91133. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  91134. */
  91135. this.attachableMeshes = null;
  91136. /**
  91137. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  91138. */
  91139. this.usePointerToAttachGizmos = true;
  91140. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  91141. // Instatiate/dispose gizmos based on pointer actions
  91142. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  91143. if (!_this.usePointerToAttachGizmos) {
  91144. return;
  91145. }
  91146. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91147. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  91148. var node = pointerInfo.pickInfo.pickedMesh;
  91149. if (_this.attachableMeshes == null) {
  91150. // Attach to the most parent node
  91151. while (node && node.parent != null) {
  91152. node = node.parent;
  91153. }
  91154. }
  91155. else {
  91156. // Attach to the parent node that is an attachableMesh
  91157. var found = false;
  91158. _this.attachableMeshes.forEach(function (mesh) {
  91159. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  91160. node = mesh;
  91161. found = true;
  91162. }
  91163. });
  91164. if (!found) {
  91165. node = null;
  91166. }
  91167. }
  91168. if (node instanceof BABYLON.AbstractMesh) {
  91169. _this.attachToMesh(node);
  91170. }
  91171. }
  91172. else {
  91173. _this.attachToMesh(null);
  91174. }
  91175. }
  91176. });
  91177. }
  91178. /**
  91179. * Attaches a set of gizmos to the specified mesh
  91180. * @param mesh The mesh the gizmo's should be attached to
  91181. */
  91182. GizmoManager.prototype.attachToMesh = function (mesh) {
  91183. if (this._attachedMesh) {
  91184. this._attachedMesh.removeBehavior(this._dragBehavior);
  91185. }
  91186. this._attachedMesh = mesh;
  91187. for (var key in this.gizmos) {
  91188. var gizmo = (this.gizmos[key]);
  91189. if (gizmo && this._gizmosEnabled[key]) {
  91190. gizmo.attachedMesh = mesh;
  91191. }
  91192. }
  91193. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  91194. this._attachedMesh.addBehavior(this._dragBehavior);
  91195. }
  91196. };
  91197. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  91198. get: function () {
  91199. return this._gizmosEnabled.positionGizmo;
  91200. },
  91201. /**
  91202. * If the position gizmo is enabled
  91203. */
  91204. set: function (value) {
  91205. if (value) {
  91206. this.gizmos.positionGizmo = this.gizmos.positionGizmo || new BABYLON.PositionGizmo();
  91207. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91208. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  91209. }
  91210. else if (this.gizmos.positionGizmo) {
  91211. this.gizmos.positionGizmo.attachedMesh = null;
  91212. }
  91213. this._gizmosEnabled.positionGizmo = value;
  91214. },
  91215. enumerable: true,
  91216. configurable: true
  91217. });
  91218. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  91219. get: function () {
  91220. return this._gizmosEnabled.rotationGizmo;
  91221. },
  91222. /**
  91223. * If the rotation gizmo is enabled
  91224. */
  91225. set: function (value) {
  91226. if (value) {
  91227. this.gizmos.rotationGizmo = this.gizmos.rotationGizmo || new BABYLON.RotationGizmo();
  91228. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  91229. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  91230. }
  91231. else if (this.gizmos.rotationGizmo) {
  91232. this.gizmos.rotationGizmo.attachedMesh = null;
  91233. }
  91234. this._gizmosEnabled.rotationGizmo = value;
  91235. },
  91236. enumerable: true,
  91237. configurable: true
  91238. });
  91239. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  91240. get: function () {
  91241. return this._gizmosEnabled.scaleGizmo;
  91242. },
  91243. /**
  91244. * If the scale gizmo is enabled
  91245. */
  91246. set: function (value) {
  91247. if (value) {
  91248. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  91249. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  91250. }
  91251. else if (this.gizmos.scaleGizmo) {
  91252. this.gizmos.scaleGizmo.attachedMesh = null;
  91253. }
  91254. this._gizmosEnabled.scaleGizmo = value;
  91255. },
  91256. enumerable: true,
  91257. configurable: true
  91258. });
  91259. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  91260. get: function () {
  91261. return this._gizmosEnabled.boundingBoxGizmo;
  91262. },
  91263. /**
  91264. * If the boundingBox gizmo is enabled
  91265. */
  91266. set: function (value) {
  91267. if (value) {
  91268. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  91269. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  91270. if (this._attachedMesh) {
  91271. this._attachedMesh.removeBehavior(this._dragBehavior);
  91272. this._attachedMesh.addBehavior(this._dragBehavior);
  91273. }
  91274. }
  91275. else if (this.gizmos.boundingBoxGizmo) {
  91276. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  91277. }
  91278. this._gizmosEnabled.boundingBoxGizmo = value;
  91279. },
  91280. enumerable: true,
  91281. configurable: true
  91282. });
  91283. /**
  91284. * Disposes of the gizmo manager
  91285. */
  91286. GizmoManager.prototype.dispose = function () {
  91287. this.scene.onPointerObservable.remove(this._pointerObserver);
  91288. for (var key in this.gizmos) {
  91289. var gizmo = (this.gizmos[key]);
  91290. if (gizmo) {
  91291. gizmo.dispose();
  91292. }
  91293. }
  91294. this._dragBehavior.detach();
  91295. this._gizmoLayer.dispose();
  91296. };
  91297. return GizmoManager;
  91298. }());
  91299. BABYLON.GizmoManager = GizmoManager;
  91300. })(BABYLON || (BABYLON = {}));
  91301. //# sourceMappingURL=babylon.gizmoManager.js.map
  91302. var BABYLON;
  91303. (function (BABYLON) {
  91304. /**
  91305. * Defines a target to use with MorphTargetManager
  91306. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91307. */
  91308. var MorphTarget = /** @class */ (function () {
  91309. /**
  91310. * Creates a new MorphTarget
  91311. * @param name defines the name of the target
  91312. * @param influence defines the influence to use
  91313. */
  91314. function MorphTarget(
  91315. /** defines the name of the target */
  91316. name, influence, scene) {
  91317. if (influence === void 0) { influence = 0; }
  91318. if (scene === void 0) { scene = null; }
  91319. this.name = name;
  91320. /**
  91321. * Gets or sets the list of animations
  91322. */
  91323. this.animations = new Array();
  91324. this._positions = null;
  91325. this._normals = null;
  91326. this._tangents = null;
  91327. /**
  91328. * Observable raised when the influence changes
  91329. */
  91330. this.onInfluenceChanged = new BABYLON.Observable();
  91331. this._animationPropertiesOverride = null;
  91332. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91333. this.influence = influence;
  91334. }
  91335. Object.defineProperty(MorphTarget.prototype, "influence", {
  91336. /**
  91337. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  91338. */
  91339. get: function () {
  91340. return this._influence;
  91341. },
  91342. set: function (influence) {
  91343. if (this._influence === influence) {
  91344. return;
  91345. }
  91346. var previous = this._influence;
  91347. this._influence = influence;
  91348. if (this.onInfluenceChanged.hasObservers) {
  91349. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  91350. }
  91351. },
  91352. enumerable: true,
  91353. configurable: true
  91354. });
  91355. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  91356. /**
  91357. * Gets or sets the animation properties override
  91358. */
  91359. get: function () {
  91360. if (!this._animationPropertiesOverride && this._scene) {
  91361. return this._scene.animationPropertiesOverride;
  91362. }
  91363. return this._animationPropertiesOverride;
  91364. },
  91365. set: function (value) {
  91366. this._animationPropertiesOverride = value;
  91367. },
  91368. enumerable: true,
  91369. configurable: true
  91370. });
  91371. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  91372. /**
  91373. * Gets a boolean defining if the target contains position data
  91374. */
  91375. get: function () {
  91376. return !!this._positions;
  91377. },
  91378. enumerable: true,
  91379. configurable: true
  91380. });
  91381. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  91382. /**
  91383. * Gets a boolean defining if the target contains normal data
  91384. */
  91385. get: function () {
  91386. return !!this._normals;
  91387. },
  91388. enumerable: true,
  91389. configurable: true
  91390. });
  91391. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  91392. /**
  91393. * Gets a boolean defining if the target contains tangent data
  91394. */
  91395. get: function () {
  91396. return !!this._tangents;
  91397. },
  91398. enumerable: true,
  91399. configurable: true
  91400. });
  91401. /**
  91402. * Affects position data to this target
  91403. * @param data defines the position data to use
  91404. */
  91405. MorphTarget.prototype.setPositions = function (data) {
  91406. this._positions = data;
  91407. };
  91408. /**
  91409. * Gets the position data stored in this target
  91410. * @returns a FloatArray containing the position data (or null if not present)
  91411. */
  91412. MorphTarget.prototype.getPositions = function () {
  91413. return this._positions;
  91414. };
  91415. /**
  91416. * Affects normal data to this target
  91417. * @param data defines the normal data to use
  91418. */
  91419. MorphTarget.prototype.setNormals = function (data) {
  91420. this._normals = data;
  91421. };
  91422. /**
  91423. * Gets the normal data stored in this target
  91424. * @returns a FloatArray containing the normal data (or null if not present)
  91425. */
  91426. MorphTarget.prototype.getNormals = function () {
  91427. return this._normals;
  91428. };
  91429. /**
  91430. * Affects tangent data to this target
  91431. * @param data defines the tangent data to use
  91432. */
  91433. MorphTarget.prototype.setTangents = function (data) {
  91434. this._tangents = data;
  91435. };
  91436. /**
  91437. * Gets the tangent data stored in this target
  91438. * @returns a FloatArray containing the tangent data (or null if not present)
  91439. */
  91440. MorphTarget.prototype.getTangents = function () {
  91441. return this._tangents;
  91442. };
  91443. /**
  91444. * Serializes the current target into a Serialization object
  91445. * @returns the serialized object
  91446. */
  91447. MorphTarget.prototype.serialize = function () {
  91448. var serializationObject = {};
  91449. serializationObject.name = this.name;
  91450. serializationObject.influence = this.influence;
  91451. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  91452. if (this.hasNormals) {
  91453. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  91454. }
  91455. if (this.hasTangents) {
  91456. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  91457. }
  91458. // Animations
  91459. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  91460. return serializationObject;
  91461. };
  91462. // Statics
  91463. /**
  91464. * Creates a new target from serialized data
  91465. * @param serializationObject defines the serialized data to use
  91466. * @returns a new MorphTarget
  91467. */
  91468. MorphTarget.Parse = function (serializationObject) {
  91469. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  91470. result.setPositions(serializationObject.positions);
  91471. if (serializationObject.normals) {
  91472. result.setNormals(serializationObject.normals);
  91473. }
  91474. if (serializationObject.tangents) {
  91475. result.setTangents(serializationObject.tangents);
  91476. }
  91477. // Animations
  91478. if (serializationObject.animations) {
  91479. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  91480. var parsedAnimation = serializationObject.animations[animationIndex];
  91481. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  91482. }
  91483. }
  91484. return result;
  91485. };
  91486. /**
  91487. * Creates a MorphTarget from mesh data
  91488. * @param mesh defines the source mesh
  91489. * @param name defines the name to use for the new target
  91490. * @param influence defines the influence to attach to the target
  91491. * @returns a new MorphTarget
  91492. */
  91493. MorphTarget.FromMesh = function (mesh, name, influence) {
  91494. if (!name) {
  91495. name = mesh.name;
  91496. }
  91497. var result = new MorphTarget(name, influence, mesh.getScene());
  91498. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91500. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  91501. }
  91502. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  91503. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  91504. }
  91505. return result;
  91506. };
  91507. return MorphTarget;
  91508. }());
  91509. BABYLON.MorphTarget = MorphTarget;
  91510. })(BABYLON || (BABYLON = {}));
  91511. //# sourceMappingURL=babylon.morphTarget.js.map
  91512. var BABYLON;
  91513. (function (BABYLON) {
  91514. /**
  91515. * This class is used to deform meshes using morphing between different targets
  91516. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  91517. */
  91518. var MorphTargetManager = /** @class */ (function () {
  91519. /**
  91520. * Creates a new MorphTargetManager
  91521. * @param scene defines the current scene
  91522. */
  91523. function MorphTargetManager(scene) {
  91524. if (scene === void 0) { scene = null; }
  91525. this._targets = new Array();
  91526. this._targetObservable = new Array();
  91527. this._activeTargets = new BABYLON.SmartArray(16);
  91528. this._supportsNormals = false;
  91529. this._supportsTangents = false;
  91530. this._vertexCount = 0;
  91531. this._uniqueId = 0;
  91532. this._tempInfluences = new Array();
  91533. if (!scene) {
  91534. scene = BABYLON.Engine.LastCreatedScene;
  91535. }
  91536. this._scene = scene;
  91537. if (this._scene) {
  91538. this._scene.morphTargetManagers.push(this);
  91539. this._uniqueId = this._scene.getUniqueId();
  91540. }
  91541. }
  91542. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  91543. /**
  91544. * Gets the unique ID of this manager
  91545. */
  91546. get: function () {
  91547. return this._uniqueId;
  91548. },
  91549. enumerable: true,
  91550. configurable: true
  91551. });
  91552. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  91553. /**
  91554. * Gets the number of vertices handled by this manager
  91555. */
  91556. get: function () {
  91557. return this._vertexCount;
  91558. },
  91559. enumerable: true,
  91560. configurable: true
  91561. });
  91562. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  91563. /**
  91564. * Gets a boolean indicating if this manager supports morphing of normals
  91565. */
  91566. get: function () {
  91567. return this._supportsNormals;
  91568. },
  91569. enumerable: true,
  91570. configurable: true
  91571. });
  91572. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  91573. /**
  91574. * Gets a boolean indicating if this manager supports morphing of tangents
  91575. */
  91576. get: function () {
  91577. return this._supportsTangents;
  91578. },
  91579. enumerable: true,
  91580. configurable: true
  91581. });
  91582. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  91583. /**
  91584. * Gets the number of targets stored in this manager
  91585. */
  91586. get: function () {
  91587. return this._targets.length;
  91588. },
  91589. enumerable: true,
  91590. configurable: true
  91591. });
  91592. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  91593. /**
  91594. * Gets the number of influencers (ie. the number of targets with influences > 0)
  91595. */
  91596. get: function () {
  91597. return this._activeTargets.length;
  91598. },
  91599. enumerable: true,
  91600. configurable: true
  91601. });
  91602. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  91603. /**
  91604. * Gets the list of influences (one per target)
  91605. */
  91606. get: function () {
  91607. return this._influences;
  91608. },
  91609. enumerable: true,
  91610. configurable: true
  91611. });
  91612. /**
  91613. * Gets the active target at specified index. An active target is a target with an influence > 0
  91614. * @param index defines the index to check
  91615. * @returns the requested target
  91616. */
  91617. MorphTargetManager.prototype.getActiveTarget = function (index) {
  91618. return this._activeTargets.data[index];
  91619. };
  91620. /**
  91621. * Gets the target at specified index
  91622. * @param index defines the index to check
  91623. * @returns the requested target
  91624. */
  91625. MorphTargetManager.prototype.getTarget = function (index) {
  91626. return this._targets[index];
  91627. };
  91628. /**
  91629. * Add a new target to this manager
  91630. * @param target defines the target to add
  91631. */
  91632. MorphTargetManager.prototype.addTarget = function (target) {
  91633. var _this = this;
  91634. this._targets.push(target);
  91635. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  91636. _this._syncActiveTargets(needUpdate);
  91637. }));
  91638. this._syncActiveTargets(true);
  91639. };
  91640. /**
  91641. * Removes a target from the manager
  91642. * @param target defines the target to remove
  91643. */
  91644. MorphTargetManager.prototype.removeTarget = function (target) {
  91645. var index = this._targets.indexOf(target);
  91646. if (index >= 0) {
  91647. this._targets.splice(index, 1);
  91648. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  91649. this._syncActiveTargets(true);
  91650. }
  91651. };
  91652. /**
  91653. * Serializes the current manager into a Serialization object
  91654. * @returns the serialized object
  91655. */
  91656. MorphTargetManager.prototype.serialize = function () {
  91657. var serializationObject = {};
  91658. serializationObject.id = this.uniqueId;
  91659. serializationObject.targets = [];
  91660. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91661. var target = _a[_i];
  91662. serializationObject.targets.push(target.serialize());
  91663. }
  91664. return serializationObject;
  91665. };
  91666. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  91667. var influenceCount = 0;
  91668. this._activeTargets.reset();
  91669. this._supportsNormals = true;
  91670. this._supportsTangents = true;
  91671. this._vertexCount = 0;
  91672. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  91673. var target = _a[_i];
  91674. this._activeTargets.push(target);
  91675. this._tempInfluences[influenceCount++] = target.influence;
  91676. var positions = target.getPositions();
  91677. if (positions) {
  91678. this._supportsNormals = this._supportsNormals && target.hasNormals;
  91679. this._supportsTangents = this._supportsTangents && target.hasTangents;
  91680. var vertexCount = positions.length / 3;
  91681. if (this._vertexCount === 0) {
  91682. this._vertexCount = vertexCount;
  91683. }
  91684. else if (this._vertexCount !== vertexCount) {
  91685. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  91686. return;
  91687. }
  91688. }
  91689. }
  91690. if (!this._influences || this._influences.length !== influenceCount) {
  91691. this._influences = new Float32Array(influenceCount);
  91692. }
  91693. for (var index = 0; index < influenceCount; index++) {
  91694. this._influences[index] = this._tempInfluences[index];
  91695. }
  91696. if (needUpdate) {
  91697. this.synchronize();
  91698. }
  91699. };
  91700. /**
  91701. * Syncrhonize the targets with all the meshes using this morph target manager
  91702. */
  91703. MorphTargetManager.prototype.synchronize = function () {
  91704. if (!this._scene) {
  91705. return;
  91706. }
  91707. // Flag meshes as dirty to resync with the active targets
  91708. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  91709. var mesh = _a[_i];
  91710. if (mesh.morphTargetManager === this) {
  91711. mesh._syncGeometryWithMorphTargetManager();
  91712. }
  91713. }
  91714. };
  91715. // Statics
  91716. /**
  91717. * Creates a new MorphTargetManager from serialized data
  91718. * @param serializationObject defines the serialized data
  91719. * @param scene defines the hosting scene
  91720. * @returns the new MorphTargetManager
  91721. */
  91722. MorphTargetManager.Parse = function (serializationObject, scene) {
  91723. var result = new MorphTargetManager(scene);
  91724. result._uniqueId = serializationObject.id;
  91725. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  91726. var targetData = _a[_i];
  91727. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  91728. }
  91729. return result;
  91730. };
  91731. return MorphTargetManager;
  91732. }());
  91733. BABYLON.MorphTargetManager = MorphTargetManager;
  91734. })(BABYLON || (BABYLON = {}));
  91735. //# sourceMappingURL=babylon.morphTargetManager.js.map
  91736. var BABYLON;
  91737. (function (BABYLON) {
  91738. var Octree = /** @class */ (function () {
  91739. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  91740. if (maxDepth === void 0) { maxDepth = 2; }
  91741. this.maxDepth = maxDepth;
  91742. this.dynamicContent = new Array();
  91743. this._maxBlockCapacity = maxBlockCapacity || 64;
  91744. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  91745. this._creationFunc = creationFunc;
  91746. }
  91747. // Methods
  91748. Octree.prototype.update = function (worldMin, worldMax, entries) {
  91749. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  91750. };
  91751. Octree.prototype.addMesh = function (entry) {
  91752. for (var index = 0; index < this.blocks.length; index++) {
  91753. var block = this.blocks[index];
  91754. block.addEntry(entry);
  91755. }
  91756. };
  91757. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  91758. this._selectionContent.reset();
  91759. for (var index = 0; index < this.blocks.length; index++) {
  91760. var block = this.blocks[index];
  91761. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  91762. }
  91763. if (allowDuplicate) {
  91764. this._selectionContent.concat(this.dynamicContent);
  91765. }
  91766. else {
  91767. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91768. }
  91769. return this._selectionContent;
  91770. };
  91771. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  91772. this._selectionContent.reset();
  91773. for (var index = 0; index < this.blocks.length; index++) {
  91774. var block = this.blocks[index];
  91775. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91776. }
  91777. if (allowDuplicate) {
  91778. this._selectionContent.concat(this.dynamicContent);
  91779. }
  91780. else {
  91781. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91782. }
  91783. return this._selectionContent;
  91784. };
  91785. Octree.prototype.intersectsRay = function (ray) {
  91786. this._selectionContent.reset();
  91787. for (var index = 0; index < this.blocks.length; index++) {
  91788. var block = this.blocks[index];
  91789. block.intersectsRay(ray, this._selectionContent);
  91790. }
  91791. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91792. return this._selectionContent;
  91793. };
  91794. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91795. target.blocks = new Array();
  91796. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91797. // Segmenting space
  91798. for (var x = 0; x < 2; x++) {
  91799. for (var y = 0; y < 2; y++) {
  91800. for (var z = 0; z < 2; z++) {
  91801. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91802. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91803. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91804. block.addEntries(entries);
  91805. target.blocks.push(block);
  91806. }
  91807. }
  91808. }
  91809. };
  91810. Octree.CreationFuncForMeshes = function (entry, block) {
  91811. var boundingInfo = entry.getBoundingInfo();
  91812. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91813. block.entries.push(entry);
  91814. }
  91815. };
  91816. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91817. var boundingInfo = entry.getBoundingInfo();
  91818. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91819. block.entries.push(entry);
  91820. }
  91821. };
  91822. return Octree;
  91823. }());
  91824. BABYLON.Octree = Octree;
  91825. })(BABYLON || (BABYLON = {}));
  91826. //# sourceMappingURL=babylon.octree.js.map
  91827. var BABYLON;
  91828. (function (BABYLON) {
  91829. var OctreeBlock = /** @class */ (function () {
  91830. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91831. this.entries = new Array();
  91832. this._boundingVectors = new Array();
  91833. this._capacity = capacity;
  91834. this._depth = depth;
  91835. this._maxDepth = maxDepth;
  91836. this._creationFunc = creationFunc;
  91837. this._minPoint = minPoint;
  91838. this._maxPoint = maxPoint;
  91839. this._boundingVectors.push(minPoint.clone());
  91840. this._boundingVectors.push(maxPoint.clone());
  91841. this._boundingVectors.push(minPoint.clone());
  91842. this._boundingVectors[2].x = maxPoint.x;
  91843. this._boundingVectors.push(minPoint.clone());
  91844. this._boundingVectors[3].y = maxPoint.y;
  91845. this._boundingVectors.push(minPoint.clone());
  91846. this._boundingVectors[4].z = maxPoint.z;
  91847. this._boundingVectors.push(maxPoint.clone());
  91848. this._boundingVectors[5].z = minPoint.z;
  91849. this._boundingVectors.push(maxPoint.clone());
  91850. this._boundingVectors[6].x = minPoint.x;
  91851. this._boundingVectors.push(maxPoint.clone());
  91852. this._boundingVectors[7].y = minPoint.y;
  91853. }
  91854. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91855. // Property
  91856. get: function () {
  91857. return this._capacity;
  91858. },
  91859. enumerable: true,
  91860. configurable: true
  91861. });
  91862. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91863. get: function () {
  91864. return this._minPoint;
  91865. },
  91866. enumerable: true,
  91867. configurable: true
  91868. });
  91869. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91870. get: function () {
  91871. return this._maxPoint;
  91872. },
  91873. enumerable: true,
  91874. configurable: true
  91875. });
  91876. // Methods
  91877. OctreeBlock.prototype.addEntry = function (entry) {
  91878. if (this.blocks) {
  91879. for (var index = 0; index < this.blocks.length; index++) {
  91880. var block = this.blocks[index];
  91881. block.addEntry(entry);
  91882. }
  91883. return;
  91884. }
  91885. this._creationFunc(entry, this);
  91886. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91887. this.createInnerBlocks();
  91888. }
  91889. };
  91890. OctreeBlock.prototype.addEntries = function (entries) {
  91891. for (var index = 0; index < entries.length; index++) {
  91892. var mesh = entries[index];
  91893. this.addEntry(mesh);
  91894. }
  91895. };
  91896. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91897. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91898. if (this.blocks) {
  91899. for (var index = 0; index < this.blocks.length; index++) {
  91900. var block = this.blocks[index];
  91901. block.select(frustumPlanes, selection, allowDuplicate);
  91902. }
  91903. return;
  91904. }
  91905. if (allowDuplicate) {
  91906. selection.concat(this.entries);
  91907. }
  91908. else {
  91909. selection.concatWithNoDuplicate(this.entries);
  91910. }
  91911. }
  91912. };
  91913. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91914. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91915. if (this.blocks) {
  91916. for (var index = 0; index < this.blocks.length; index++) {
  91917. var block = this.blocks[index];
  91918. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91919. }
  91920. return;
  91921. }
  91922. if (allowDuplicate) {
  91923. selection.concat(this.entries);
  91924. }
  91925. else {
  91926. selection.concatWithNoDuplicate(this.entries);
  91927. }
  91928. }
  91929. };
  91930. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91931. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91932. if (this.blocks) {
  91933. for (var index = 0; index < this.blocks.length; index++) {
  91934. var block = this.blocks[index];
  91935. block.intersectsRay(ray, selection);
  91936. }
  91937. return;
  91938. }
  91939. selection.concatWithNoDuplicate(this.entries);
  91940. }
  91941. };
  91942. OctreeBlock.prototype.createInnerBlocks = function () {
  91943. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91944. };
  91945. return OctreeBlock;
  91946. }());
  91947. BABYLON.OctreeBlock = OctreeBlock;
  91948. })(BABYLON || (BABYLON = {}));
  91949. //# sourceMappingURL=babylon.octreeBlock.js.map
  91950. var BABYLON;
  91951. (function (BABYLON) {
  91952. /**
  91953. * Postprocess used to generate anaglyphic rendering
  91954. */
  91955. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91956. __extends(AnaglyphPostProcess, _super);
  91957. /**
  91958. * Creates a new AnaglyphPostProcess
  91959. * @param name defines postprocess name
  91960. * @param options defines creation options or target ratio scale
  91961. * @param rigCameras defines cameras using this postprocess
  91962. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91963. * @param engine defines hosting engine
  91964. * @param reusable defines if the postprocess will be reused multiple times per frame
  91965. */
  91966. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91967. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91968. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91969. _this.onApplyObservable.add(function (effect) {
  91970. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91971. });
  91972. return _this;
  91973. }
  91974. return AnaglyphPostProcess;
  91975. }(BABYLON.PostProcess));
  91976. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91977. })(BABYLON || (BABYLON = {}));
  91978. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91979. var BABYLON;
  91980. (function (BABYLON) {
  91981. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  91982. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  91983. });
  91984. /**
  91985. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91986. */
  91987. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91988. __extends(AnaglyphArcRotateCamera, _super);
  91989. /**
  91990. * Creates a new AnaglyphArcRotateCamera
  91991. * @param name defines camera name
  91992. * @param alpha defines alpha angle (in radians)
  91993. * @param beta defines beta angle (in radians)
  91994. * @param radius defines radius
  91995. * @param target defines camera target
  91996. * @param interaxialDistance defines distance between each color axis
  91997. * @param scene defines the hosting scene
  91998. */
  91999. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92000. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92001. _this.interaxialDistance = interaxialDistance;
  92002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92003. return _this;
  92004. }
  92005. /**
  92006. * Gets camera class name
  92007. * @returns AnaglyphArcRotateCamera
  92008. */
  92009. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92010. return "AnaglyphArcRotateCamera";
  92011. };
  92012. return AnaglyphArcRotateCamera;
  92013. }(BABYLON.ArcRotateCamera));
  92014. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92015. })(BABYLON || (BABYLON = {}));
  92016. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  92017. var BABYLON;
  92018. (function (BABYLON) {
  92019. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  92020. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92021. });
  92022. /**
  92023. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92024. */
  92025. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92026. __extends(AnaglyphFreeCamera, _super);
  92027. /**
  92028. * Creates a new AnaglyphFreeCamera
  92029. * @param name defines camera name
  92030. * @param position defines initial position
  92031. * @param interaxialDistance defines distance between each color axis
  92032. * @param scene defines the hosting scene
  92033. */
  92034. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92035. var _this = _super.call(this, name, position, scene) || this;
  92036. _this.interaxialDistance = interaxialDistance;
  92037. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92038. return _this;
  92039. }
  92040. /**
  92041. * Gets camera class name
  92042. * @returns AnaglyphFreeCamera
  92043. */
  92044. AnaglyphFreeCamera.prototype.getClassName = function () {
  92045. return "AnaglyphFreeCamera";
  92046. };
  92047. return AnaglyphFreeCamera;
  92048. }(BABYLON.FreeCamera));
  92049. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92050. })(BABYLON || (BABYLON = {}));
  92051. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  92052. var BABYLON;
  92053. (function (BABYLON) {
  92054. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  92055. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92056. });
  92057. /**
  92058. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92059. */
  92060. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92061. __extends(AnaglyphGamepadCamera, _super);
  92062. /**
  92063. * Creates a new AnaglyphGamepadCamera
  92064. * @param name defines camera name
  92065. * @param position defines initial position
  92066. * @param interaxialDistance defines distance between each color axis
  92067. * @param scene defines the hosting scene
  92068. */
  92069. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92070. var _this = _super.call(this, name, position, scene) || this;
  92071. _this.interaxialDistance = interaxialDistance;
  92072. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92073. return _this;
  92074. }
  92075. /**
  92076. * Gets camera class name
  92077. * @returns AnaglyphGamepadCamera
  92078. */
  92079. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92080. return "AnaglyphGamepadCamera";
  92081. };
  92082. return AnaglyphGamepadCamera;
  92083. }(BABYLON.GamepadCamera));
  92084. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92085. })(BABYLON || (BABYLON = {}));
  92086. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  92087. var BABYLON;
  92088. (function (BABYLON) {
  92089. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  92090. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  92091. });
  92092. /**
  92093. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92094. */
  92095. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92096. __extends(AnaglyphUniversalCamera, _super);
  92097. /**
  92098. * Creates a new AnaglyphUniversalCamera
  92099. * @param name defines camera name
  92100. * @param position defines initial position
  92101. * @param interaxialDistance defines distance between each color axis
  92102. * @param scene defines the hosting scene
  92103. */
  92104. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92105. var _this = _super.call(this, name, position, scene) || this;
  92106. _this.interaxialDistance = interaxialDistance;
  92107. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92108. return _this;
  92109. }
  92110. /**
  92111. * Gets camera class name
  92112. * @returns AnaglyphUniversalCamera
  92113. */
  92114. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92115. return "AnaglyphUniversalCamera";
  92116. };
  92117. return AnaglyphUniversalCamera;
  92118. }(BABYLON.UniversalCamera));
  92119. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92120. })(BABYLON || (BABYLON = {}));
  92121. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  92122. var BABYLON;
  92123. (function (BABYLON) {
  92124. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  92125. __extends(StereoscopicInterlacePostProcess, _super);
  92126. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  92127. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  92128. _this._passedProcess = rigCameras[0]._rigPostProcess;
  92129. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92130. _this.onSizeChangedObservable.add(function () {
  92131. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  92132. });
  92133. _this.onApplyObservable.add(function (effect) {
  92134. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  92135. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  92136. });
  92137. return _this;
  92138. }
  92139. return StereoscopicInterlacePostProcess;
  92140. }(BABYLON.PostProcess));
  92141. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  92142. })(BABYLON || (BABYLON = {}));
  92143. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  92144. var BABYLON;
  92145. (function (BABYLON) {
  92146. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  92147. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92148. });
  92149. /**
  92150. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92151. */
  92152. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92153. __extends(StereoscopicArcRotateCamera, _super);
  92154. /**
  92155. * Creates a new StereoscopicArcRotateCamera
  92156. * @param name defines camera name
  92157. * @param alpha defines alpha angle (in radians)
  92158. * @param beta defines beta angle (in radians)
  92159. * @param radius defines radius
  92160. * @param target defines camera target
  92161. * @param interaxialDistance defines distance between each color axis
  92162. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92163. * @param scene defines the hosting scene
  92164. */
  92165. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92166. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92167. _this.interaxialDistance = interaxialDistance;
  92168. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92169. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92170. return _this;
  92171. }
  92172. /**
  92173. * Gets camera class name
  92174. * @returns StereoscopicArcRotateCamera
  92175. */
  92176. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92177. return "StereoscopicArcRotateCamera";
  92178. };
  92179. return StereoscopicArcRotateCamera;
  92180. }(BABYLON.ArcRotateCamera));
  92181. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92182. })(BABYLON || (BABYLON = {}));
  92183. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  92184. var BABYLON;
  92185. (function (BABYLON) {
  92186. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92187. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92188. });
  92189. /**
  92190. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92191. */
  92192. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92193. __extends(StereoscopicFreeCamera, _super);
  92194. /**
  92195. * Creates a new StereoscopicFreeCamera
  92196. * @param name defines camera name
  92197. * @param position defines initial position
  92198. * @param interaxialDistance defines distance between each color axis
  92199. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92200. * @param scene defines the hosting scene
  92201. */
  92202. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92203. var _this = _super.call(this, name, position, scene) || this;
  92204. _this.interaxialDistance = interaxialDistance;
  92205. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92206. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92207. return _this;
  92208. }
  92209. /**
  92210. * Gets camera class name
  92211. * @returns StereoscopicFreeCamera
  92212. */
  92213. StereoscopicFreeCamera.prototype.getClassName = function () {
  92214. return "StereoscopicFreeCamera";
  92215. };
  92216. return StereoscopicFreeCamera;
  92217. }(BABYLON.FreeCamera));
  92218. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92219. })(BABYLON || (BABYLON = {}));
  92220. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  92221. var BABYLON;
  92222. (function (BABYLON) {
  92223. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  92224. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92225. });
  92226. /**
  92227. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92228. */
  92229. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92230. __extends(StereoscopicGamepadCamera, _super);
  92231. /**
  92232. * Creates a new StereoscopicGamepadCamera
  92233. * @param name defines camera name
  92234. * @param position defines initial position
  92235. * @param interaxialDistance defines distance between each color axis
  92236. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92237. * @param scene defines the hosting scene
  92238. */
  92239. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92240. var _this = _super.call(this, name, position, scene) || this;
  92241. _this.interaxialDistance = interaxialDistance;
  92242. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92243. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92244. return _this;
  92245. }
  92246. /**
  92247. * Gets camera class name
  92248. * @returns StereoscopicGamepadCamera
  92249. */
  92250. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92251. return "StereoscopicGamepadCamera";
  92252. };
  92253. return StereoscopicGamepadCamera;
  92254. }(BABYLON.GamepadCamera));
  92255. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92256. })(BABYLON || (BABYLON = {}));
  92257. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  92258. var BABYLON;
  92259. (function (BABYLON) {
  92260. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  92261. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  92262. });
  92263. /**
  92264. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92265. */
  92266. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92267. __extends(StereoscopicUniversalCamera, _super);
  92268. /**
  92269. * Creates a new StereoscopicUniversalCamera
  92270. * @param name defines camera name
  92271. * @param position defines initial position
  92272. * @param interaxialDistance defines distance between each color axis
  92273. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92274. * @param scene defines the hosting scene
  92275. */
  92276. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92277. var _this = _super.call(this, name, position, scene) || this;
  92278. _this.interaxialDistance = interaxialDistance;
  92279. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92280. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92281. return _this;
  92282. }
  92283. /**
  92284. * Gets camera class name
  92285. * @returns StereoscopicUniversalCamera
  92286. */
  92287. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92288. return "StereoscopicUniversalCamera";
  92289. };
  92290. return StereoscopicUniversalCamera;
  92291. }(BABYLON.UniversalCamera));
  92292. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92293. })(BABYLON || (BABYLON = {}));
  92294. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  92295. var BABYLON;
  92296. (function (BABYLON) {
  92297. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  92298. __extends(VRDistortionCorrectionPostProcess, _super);
  92299. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  92300. var _this = _super.call(this, name, "vrDistortionCorrection", [
  92301. 'LensCenter',
  92302. 'Scale',
  92303. 'ScaleIn',
  92304. 'HmdWarpParam'
  92305. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  92306. _this._isRightEye = isRightEye;
  92307. _this._distortionFactors = vrMetrics.distortionK;
  92308. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  92309. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  92310. _this.adaptScaleToCurrentViewport = true;
  92311. _this.onSizeChangedObservable.add(function () {
  92312. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  92313. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  92314. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  92315. });
  92316. _this.onApplyObservable.add(function (effect) {
  92317. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  92318. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  92319. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  92320. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  92321. });
  92322. return _this;
  92323. }
  92324. return VRDistortionCorrectionPostProcess;
  92325. }(BABYLON.PostProcess));
  92326. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  92327. })(BABYLON || (BABYLON = {}));
  92328. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  92329. var BABYLON;
  92330. (function (BABYLON) {
  92331. /**
  92332. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  92333. * Screen rotation is taken into account.
  92334. */
  92335. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  92336. function FreeCameraDeviceOrientationInput() {
  92337. var _this = this;
  92338. this._screenOrientationAngle = 0;
  92339. this._screenQuaternion = new BABYLON.Quaternion();
  92340. this._alpha = 0;
  92341. this._beta = 0;
  92342. this._gamma = 0;
  92343. this._orientationChanged = function () {
  92344. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  92345. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  92346. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  92347. };
  92348. this._deviceOrientation = function (evt) {
  92349. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  92350. _this._beta = evt.beta !== null ? evt.beta : 0;
  92351. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  92352. };
  92353. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  92354. this._orientationChanged();
  92355. }
  92356. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  92357. get: function () {
  92358. return this._camera;
  92359. },
  92360. set: function (camera) {
  92361. this._camera = camera;
  92362. if (this._camera != null && !this._camera.rotationQuaternion) {
  92363. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  92364. }
  92365. },
  92366. enumerable: true,
  92367. configurable: true
  92368. });
  92369. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92370. window.addEventListener("orientationchange", this._orientationChanged);
  92371. window.addEventListener("deviceorientation", this._deviceOrientation);
  92372. //In certain cases, the attach control is called AFTER orientation was changed,
  92373. //So this is needed.
  92374. this._orientationChanged();
  92375. };
  92376. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  92377. window.removeEventListener("orientationchange", this._orientationChanged);
  92378. window.removeEventListener("deviceorientation", this._deviceOrientation);
  92379. };
  92380. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  92381. //if no device orientation provided, don't update the rotation.
  92382. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  92383. if (!this._alpha)
  92384. return;
  92385. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  92386. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  92387. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  92388. //Mirror on XY Plane
  92389. this._camera.rotationQuaternion.z *= -1;
  92390. this._camera.rotationQuaternion.w *= -1;
  92391. };
  92392. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  92393. return "FreeCameraDeviceOrientationInput";
  92394. };
  92395. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  92396. return "deviceOrientation";
  92397. };
  92398. return FreeCameraDeviceOrientationInput;
  92399. }());
  92400. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  92401. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  92402. })(BABYLON || (BABYLON = {}));
  92403. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  92404. var BABYLON;
  92405. (function (BABYLON) {
  92406. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  92407. function ArcRotateCameraVRDeviceOrientationInput() {
  92408. this.alphaCorrection = 1;
  92409. this.betaCorrection = 1;
  92410. this.gammaCorrection = 1;
  92411. this._alpha = 0;
  92412. this._gamma = 0;
  92413. this._dirty = false;
  92414. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  92415. }
  92416. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  92417. this.camera.attachControl(element, noPreventDefault);
  92418. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  92419. };
  92420. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  92421. if (evt.alpha !== null) {
  92422. this._alpha = +evt.alpha | 0;
  92423. }
  92424. if (evt.gamma !== null) {
  92425. this._gamma = +evt.gamma | 0;
  92426. }
  92427. this._dirty = true;
  92428. };
  92429. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  92430. if (this._dirty) {
  92431. this._dirty = false;
  92432. if (this._gamma < 0) {
  92433. this._gamma = 180 + this._gamma;
  92434. }
  92435. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  92436. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  92437. }
  92438. };
  92439. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  92440. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  92441. };
  92442. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  92443. return "ArcRotateCameraVRDeviceOrientationInput";
  92444. };
  92445. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  92446. return "VRDeviceOrientation";
  92447. };
  92448. return ArcRotateCameraVRDeviceOrientationInput;
  92449. }());
  92450. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  92451. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  92452. })(BABYLON || (BABYLON = {}));
  92453. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  92454. var BABYLON;
  92455. (function (BABYLON) {
  92456. var VRCameraMetrics = /** @class */ (function () {
  92457. function VRCameraMetrics() {
  92458. this.compensateDistortion = true;
  92459. }
  92460. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  92461. get: function () {
  92462. return this.hResolution / (2 * this.vResolution);
  92463. },
  92464. enumerable: true,
  92465. configurable: true
  92466. });
  92467. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  92468. get: function () {
  92469. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  92470. },
  92471. enumerable: true,
  92472. configurable: true
  92473. });
  92474. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  92475. get: function () {
  92476. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92477. var h = (4 * meters) / this.hScreenSize;
  92478. return BABYLON.Matrix.Translation(h, 0, 0);
  92479. },
  92480. enumerable: true,
  92481. configurable: true
  92482. });
  92483. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  92484. get: function () {
  92485. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  92486. var h = (4 * meters) / this.hScreenSize;
  92487. return BABYLON.Matrix.Translation(-h, 0, 0);
  92488. },
  92489. enumerable: true,
  92490. configurable: true
  92491. });
  92492. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  92493. get: function () {
  92494. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  92495. },
  92496. enumerable: true,
  92497. configurable: true
  92498. });
  92499. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  92500. get: function () {
  92501. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  92502. },
  92503. enumerable: true,
  92504. configurable: true
  92505. });
  92506. VRCameraMetrics.GetDefault = function () {
  92507. var result = new VRCameraMetrics();
  92508. result.hResolution = 1280;
  92509. result.vResolution = 800;
  92510. result.hScreenSize = 0.149759993;
  92511. result.vScreenSize = 0.0935999975;
  92512. result.vScreenCenter = 0.0467999987;
  92513. result.eyeToScreenDistance = 0.0410000011;
  92514. result.lensSeparationDistance = 0.0635000020;
  92515. result.interpupillaryDistance = 0.0640000030;
  92516. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  92517. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  92518. result.postProcessScaleFactor = 1.714605507808412;
  92519. result.lensCenterOffset = 0.151976421;
  92520. return result;
  92521. };
  92522. return VRCameraMetrics;
  92523. }());
  92524. BABYLON.VRCameraMetrics = VRCameraMetrics;
  92525. })(BABYLON || (BABYLON = {}));
  92526. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  92527. var BABYLON;
  92528. (function (BABYLON) {
  92529. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  92530. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92531. });
  92532. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  92533. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  92534. });
  92535. /**
  92536. * This represents a WebVR camera.
  92537. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  92538. * @example http://doc.babylonjs.com/how_to/webvr_camera
  92539. */
  92540. var WebVRFreeCamera = /** @class */ (function (_super) {
  92541. __extends(WebVRFreeCamera, _super);
  92542. /**
  92543. * Instantiates a WebVRFreeCamera.
  92544. * @param name The name of the WebVRFreeCamera
  92545. * @param position The starting anchor position for the camera
  92546. * @param scene The scene the camera belongs to
  92547. * @param webVROptions a set of customizable options for the webVRCamera
  92548. */
  92549. function WebVRFreeCamera(name, position, scene, webVROptions) {
  92550. if (webVROptions === void 0) { webVROptions = {}; }
  92551. var _this = _super.call(this, name, position, scene) || this;
  92552. _this.webVROptions = webVROptions;
  92553. /**
  92554. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  92555. */
  92556. _this._vrDevice = null;
  92557. /**
  92558. * The rawPose of the vrDevice.
  92559. */
  92560. _this.rawPose = null;
  92561. _this._specsVersion = "1.1";
  92562. _this._attached = false;
  92563. _this._descendants = [];
  92564. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  92565. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  92566. /** @hidden */
  92567. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  92568. _this._standingMatrix = null;
  92569. /**
  92570. * Represents device position in babylon space.
  92571. */
  92572. _this.devicePosition = BABYLON.Vector3.Zero();
  92573. /**
  92574. * Represents device rotation in babylon space.
  92575. */
  92576. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  92577. /**
  92578. * The scale of the device to be used when translating from device space to babylon space.
  92579. */
  92580. _this.deviceScaleFactor = 1;
  92581. _this._deviceToWorld = BABYLON.Matrix.Identity();
  92582. _this._worldToDevice = BABYLON.Matrix.Identity();
  92583. /**
  92584. * References to the webVR controllers for the vrDevice.
  92585. */
  92586. _this.controllers = [];
  92587. /**
  92588. * Emits an event when a controller is attached.
  92589. */
  92590. _this.onControllersAttachedObservable = new BABYLON.Observable();
  92591. /**
  92592. * Emits an event when a controller's mesh has been loaded;
  92593. */
  92594. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92595. /**
  92596. * Emits an event when the HMD's pose has been updated.
  92597. */
  92598. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  92599. _this._poseSet = false;
  92600. /**
  92601. * If the rig cameras be used as parent instead of this camera.
  92602. */
  92603. _this.rigParenting = true;
  92604. _this._defaultHeight = undefined;
  92605. _this._workingVector = BABYLON.Vector3.Zero();
  92606. _this._oneVector = BABYLON.Vector3.One();
  92607. _this._workingMatrix = BABYLON.Matrix.Identity();
  92608. _this._cache.position = BABYLON.Vector3.Zero();
  92609. if (webVROptions.defaultHeight) {
  92610. _this._defaultHeight = webVROptions.defaultHeight;
  92611. _this.position.y = _this._defaultHeight;
  92612. }
  92613. _this.minZ = 0.1;
  92614. //legacy support - the compensation boolean was removed.
  92615. if (arguments.length === 5) {
  92616. _this.webVROptions = arguments[4];
  92617. }
  92618. // default webVR options
  92619. if (_this.webVROptions.trackPosition == undefined) {
  92620. _this.webVROptions.trackPosition = true;
  92621. }
  92622. if (_this.webVROptions.controllerMeshes == undefined) {
  92623. _this.webVROptions.controllerMeshes = true;
  92624. }
  92625. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  92626. _this.webVROptions.defaultLightingOnControllers = true;
  92627. }
  92628. _this.rotationQuaternion = new BABYLON.Quaternion();
  92629. if (_this.webVROptions && _this.webVROptions.positionScale) {
  92630. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  92631. }
  92632. //enable VR
  92633. var engine = _this.getEngine();
  92634. _this._onVREnabled = function (success) { if (success) {
  92635. _this.initControllers();
  92636. } };
  92637. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  92638. engine.initWebVR().add(function (event) {
  92639. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  92640. return;
  92641. }
  92642. _this._vrDevice = event.vrDisplay;
  92643. //reset the rig parameters.
  92644. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  92645. if (_this._attached) {
  92646. _this.getEngine().enableVR();
  92647. }
  92648. });
  92649. if (typeof (VRFrameData) !== "undefined")
  92650. _this._frameData = new VRFrameData();
  92651. /**
  92652. * The idea behind the following lines:
  92653. * objects that have the camera as parent should actually have the rig cameras as a parent.
  92654. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  92655. * the second will not show it correctly.
  92656. *
  92657. * To solve this - each object that has the camera as parent will be added to a protected array.
  92658. * When the rig camera renders, it will take this array and set all of those to be its children.
  92659. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  92660. * Amazing!
  92661. */
  92662. scene.onBeforeCameraRenderObservable.add(function (camera) {
  92663. if (camera.parent === _this && _this.rigParenting) {
  92664. _this._descendants = _this.getDescendants(true, function (n) {
  92665. // don't take the cameras or the controllers!
  92666. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  92667. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  92668. return !isController && !isRigCamera;
  92669. });
  92670. _this._descendants.forEach(function (node) {
  92671. node.parent = camera;
  92672. });
  92673. }
  92674. });
  92675. scene.onAfterCameraRenderObservable.add(function (camera) {
  92676. if (camera.parent === _this && _this.rigParenting) {
  92677. _this._descendants.forEach(function (node) {
  92678. node.parent = _this;
  92679. });
  92680. }
  92681. });
  92682. return _this;
  92683. }
  92684. /**
  92685. * Gets the device distance from the ground in meters.
  92686. * @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.
  92687. */
  92688. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  92689. if (this._standingMatrix) {
  92690. // Add standing matrix offset to get real offset from ground in room
  92691. this._standingMatrix.getTranslationToRef(this._workingVector);
  92692. return this._deviceRoomPosition.y + this._workingVector.y;
  92693. }
  92694. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  92695. return this._defaultHeight || 0;
  92696. };
  92697. /**
  92698. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92699. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  92700. */
  92701. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  92702. var _this = this;
  92703. if (callback === void 0) { callback = function (bool) { }; }
  92704. // Use standing matrix if available
  92705. this.getEngine().initWebVRAsync().then(function (result) {
  92706. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  92707. callback(false);
  92708. }
  92709. else {
  92710. _this._standingMatrix = new BABYLON.Matrix();
  92711. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  92712. if (!_this.getScene().useRightHandedSystem) {
  92713. [2, 6, 8, 9, 14].forEach(function (num) {
  92714. if (_this._standingMatrix) {
  92715. _this._standingMatrix.m[num] *= -1;
  92716. }
  92717. });
  92718. }
  92719. callback(true);
  92720. }
  92721. });
  92722. };
  92723. /**
  92724. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  92725. * @returns A promise with a boolean set to if the standing matrix is supported.
  92726. */
  92727. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  92728. var _this = this;
  92729. return new Promise(function (res, rej) {
  92730. _this.useStandingMatrix(function (supported) {
  92731. res(supported);
  92732. });
  92733. });
  92734. };
  92735. /**
  92736. * Disposes the camera
  92737. */
  92738. WebVRFreeCamera.prototype.dispose = function () {
  92739. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  92740. _super.prototype.dispose.call(this);
  92741. };
  92742. /**
  92743. * Gets a vrController by name.
  92744. * @param name The name of the controller to retreive
  92745. * @returns the controller matching the name specified or null if not found
  92746. */
  92747. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  92748. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  92749. var gp = _a[_i];
  92750. if (gp.hand === name) {
  92751. return gp;
  92752. }
  92753. }
  92754. return null;
  92755. };
  92756. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  92757. /**
  92758. * The controller corrisponding to the users left hand.
  92759. */
  92760. get: function () {
  92761. if (!this._leftController) {
  92762. this._leftController = this.getControllerByName("left");
  92763. }
  92764. return this._leftController;
  92765. },
  92766. enumerable: true,
  92767. configurable: true
  92768. });
  92769. ;
  92770. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  92771. /**
  92772. * The controller corrisponding to the users right hand.
  92773. */
  92774. get: function () {
  92775. if (!this._rightController) {
  92776. this._rightController = this.getControllerByName("right");
  92777. }
  92778. return this._rightController;
  92779. },
  92780. enumerable: true,
  92781. configurable: true
  92782. });
  92783. ;
  92784. /**
  92785. * Casts a ray forward from the vrCamera's gaze.
  92786. * @param length Length of the ray (default: 100)
  92787. * @returns the ray corrisponding to the gaze
  92788. */
  92789. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  92790. if (length === void 0) { length = 100; }
  92791. if (this.leftCamera) {
  92792. // Use left eye to avoid computation to compute center on every call
  92793. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  92794. }
  92795. else {
  92796. return _super.prototype.getForwardRay.call(this, length);
  92797. }
  92798. };
  92799. /**
  92800. * Updates the camera based on device's frame data
  92801. */
  92802. WebVRFreeCamera.prototype._checkInputs = function () {
  92803. if (this._vrDevice && this._vrDevice.isPresenting) {
  92804. this._vrDevice.getFrameData(this._frameData);
  92805. this.updateFromDevice(this._frameData.pose);
  92806. }
  92807. _super.prototype._checkInputs.call(this);
  92808. };
  92809. /**
  92810. * Updates the poseControlled values based on the input device pose.
  92811. * @param poseData Pose coming from the device
  92812. */
  92813. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  92814. if (poseData && poseData.orientation) {
  92815. this.rawPose = poseData;
  92816. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  92817. if (this.getScene().useRightHandedSystem) {
  92818. this._deviceRoomRotationQuaternion.z *= -1;
  92819. this._deviceRoomRotationQuaternion.w *= -1;
  92820. }
  92821. if (this.webVROptions.trackPosition && this.rawPose.position) {
  92822. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  92823. if (this.getScene().useRightHandedSystem) {
  92824. this._deviceRoomPosition.z *= -1;
  92825. }
  92826. }
  92827. this._poseSet = true;
  92828. }
  92829. };
  92830. /**
  92831. * WebVR's attach control will start broadcasting frames to the device.
  92832. * Note that in certain browsers (chrome for example) this function must be called
  92833. * within a user-interaction callback. Example:
  92834. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  92835. *
  92836. * @param element html element to attach the vrDevice to
  92837. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  92838. */
  92839. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  92840. _super.prototype.attachControl.call(this, element, noPreventDefault);
  92841. this._attached = true;
  92842. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  92843. if (this._vrDevice) {
  92844. this.getEngine().enableVR();
  92845. }
  92846. };
  92847. /**
  92848. * Detaches the camera from the html element and disables VR
  92849. *
  92850. * @param element html element to detach from
  92851. */
  92852. WebVRFreeCamera.prototype.detachControl = function (element) {
  92853. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  92854. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  92855. _super.prototype.detachControl.call(this, element);
  92856. this._attached = false;
  92857. this.getEngine().disableVR();
  92858. };
  92859. /**
  92860. * @returns the name of this class
  92861. */
  92862. WebVRFreeCamera.prototype.getClassName = function () {
  92863. return "WebVRFreeCamera";
  92864. };
  92865. /**
  92866. * Calls resetPose on the vrDisplay
  92867. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  92868. */
  92869. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  92870. //uses the vrDisplay's "resetPose()".
  92871. //pitch and roll won't be affected.
  92872. this._vrDevice.resetPose();
  92873. };
  92874. /**
  92875. * Updates the rig cameras (left and right eye)
  92876. */
  92877. WebVRFreeCamera.prototype._updateRigCameras = function () {
  92878. var camLeft = this._rigCameras[0];
  92879. var camRight = this._rigCameras[1];
  92880. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92881. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  92882. camLeft.position.copyFrom(this._deviceRoomPosition);
  92883. camRight.position.copyFrom(this._deviceRoomPosition);
  92884. };
  92885. /**
  92886. * Updates the cached values of the camera
  92887. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  92888. */
  92889. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  92890. var _this = this;
  92891. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  92892. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  92893. if (!this.updateCacheCalled) {
  92894. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  92895. this.updateCacheCalled = true;
  92896. this.update();
  92897. }
  92898. // Set working vector to the device position in room space rotated by the new rotation
  92899. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  92900. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  92901. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  92902. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  92903. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  92904. // Add translation from anchor position
  92905. this._deviceToWorld.getTranslationToRef(this._workingVector);
  92906. this._workingVector.addInPlace(this.position);
  92907. this._workingVector.subtractInPlace(this._cache.position);
  92908. this._deviceToWorld.setTranslation(this._workingVector);
  92909. // Set an inverted matrix to be used when updating the camera
  92910. this._deviceToWorld.invertToRef(this._worldToDevice);
  92911. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  92912. this.controllers.forEach(function (controller) {
  92913. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  92914. controller.update();
  92915. });
  92916. }
  92917. if (!ignoreParentClass) {
  92918. _super.prototype._updateCache.call(this);
  92919. }
  92920. this.updateCacheCalled = false;
  92921. };
  92922. /**
  92923. * Updates the current device position and rotation in the babylon world
  92924. */
  92925. WebVRFreeCamera.prototype.update = function () {
  92926. // Get current device position in babylon world
  92927. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  92928. // Get current device rotation in babylon world
  92929. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  92930. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  92931. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  92932. if (this._poseSet) {
  92933. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  92934. }
  92935. _super.prototype.update.call(this);
  92936. };
  92937. /**
  92938. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  92939. * @returns an identity matrix
  92940. */
  92941. WebVRFreeCamera.prototype._getViewMatrix = function () {
  92942. return BABYLON.Matrix.Identity();
  92943. };
  92944. /**
  92945. * This function is called by the two RIG cameras.
  92946. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  92947. */
  92948. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  92949. var _this = this;
  92950. // Update the parent camera prior to using a child camera to avoid desynchronization
  92951. var parentCamera = this._cameraRigParams["parentCamera"];
  92952. parentCamera._updateCache();
  92953. //WebVR 1.1
  92954. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  92955. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  92956. if (!this.getScene().useRightHandedSystem) {
  92957. [2, 6, 8, 9, 14].forEach(function (num) {
  92958. _this._webvrViewMatrix.m[num] *= -1;
  92959. });
  92960. }
  92961. // update the camera rotation matrix
  92962. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  92963. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  92964. // Computing target and final matrix
  92965. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  92966. // should the view matrix be updated with scale and position offset?
  92967. if (parentCamera.deviceScaleFactor !== 1) {
  92968. this._webvrViewMatrix.invert();
  92969. // scale the position, if set
  92970. if (parentCamera.deviceScaleFactor) {
  92971. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  92972. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  92973. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  92974. }
  92975. this._webvrViewMatrix.invert();
  92976. }
  92977. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  92978. // Compute global position
  92979. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  92980. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  92981. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  92982. this._workingMatrix.getTranslationToRef(this._globalPosition);
  92983. this._markSyncedWithParent();
  92984. return this._webvrViewMatrix;
  92985. };
  92986. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  92987. var _this = this;
  92988. var parentCamera = this.parent;
  92989. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  92990. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  92991. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  92992. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  92993. //babylon compatible matrix
  92994. if (!this.getScene().useRightHandedSystem) {
  92995. [8, 9, 10, 11].forEach(function (num) {
  92996. _this._projectionMatrix.m[num] *= -1;
  92997. });
  92998. }
  92999. return this._projectionMatrix;
  93000. };
  93001. /**
  93002. * Initializes the controllers and their meshes
  93003. */
  93004. WebVRFreeCamera.prototype.initControllers = function () {
  93005. var _this = this;
  93006. this.controllers = [];
  93007. var manager = this.getScene().gamepadManager;
  93008. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  93009. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93010. var webVrController = gamepad;
  93011. if (webVrController.defaultModel) {
  93012. webVrController.defaultModel.setEnabled(false);
  93013. }
  93014. if (webVrController.hand === "right") {
  93015. _this._rightController = null;
  93016. }
  93017. if (webVrController.hand === "left") {
  93018. _this._leftController = null;
  93019. }
  93020. var controllerIndex = _this.controllers.indexOf(webVrController);
  93021. if (controllerIndex !== -1) {
  93022. _this.controllers.splice(controllerIndex, 1);
  93023. }
  93024. }
  93025. });
  93026. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  93027. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  93028. var webVrController_1 = gamepad;
  93029. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  93030. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  93031. if (_this.webVROptions.controllerMeshes) {
  93032. if (webVrController_1.defaultModel) {
  93033. webVrController_1.defaultModel.setEnabled(true);
  93034. }
  93035. else {
  93036. // Load the meshes
  93037. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  93038. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  93039. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  93040. if (_this.webVROptions.defaultLightingOnControllers) {
  93041. if (!_this._lightOnControllers) {
  93042. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  93043. }
  93044. var activateLightOnSubMeshes_1 = function (mesh, light) {
  93045. var children = mesh.getChildren();
  93046. if (children.length !== 0) {
  93047. children.forEach(function (mesh) {
  93048. light.includedOnlyMeshes.push(mesh);
  93049. activateLightOnSubMeshes_1(mesh, light);
  93050. });
  93051. }
  93052. };
  93053. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  93054. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  93055. }
  93056. });
  93057. }
  93058. }
  93059. webVrController_1.attachToPoseControlledCamera(_this);
  93060. // since this is async - sanity check. Is the controller already stored?
  93061. if (_this.controllers.indexOf(webVrController_1) === -1) {
  93062. //add to the controllers array
  93063. _this.controllers.push(webVrController_1);
  93064. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  93065. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  93066. // So we're overriding setting left & right manually to be sure
  93067. var firstViveWandDetected = false;
  93068. for (var i = 0; i < _this.controllers.length; i++) {
  93069. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93070. if (!firstViveWandDetected) {
  93071. firstViveWandDetected = true;
  93072. _this.controllers[i].hand = "left";
  93073. }
  93074. else {
  93075. _this.controllers[i].hand = "right";
  93076. }
  93077. }
  93078. }
  93079. //did we find enough controllers? Great! let the developer know.
  93080. if (_this.controllers.length >= 2) {
  93081. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  93082. }
  93083. }
  93084. }
  93085. });
  93086. };
  93087. return WebVRFreeCamera;
  93088. }(BABYLON.FreeCamera));
  93089. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  93090. })(BABYLON || (BABYLON = {}));
  93091. //# sourceMappingURL=babylon.webVRCamera.js.map
  93092. var BABYLON;
  93093. (function (BABYLON) {
  93094. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  93095. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  93096. });
  93097. // We're mainly based on the logic defined into the FreeCamera code
  93098. /**
  93099. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  93100. * being tilted forward or back and left or right.
  93101. */
  93102. var DeviceOrientationCamera = /** @class */ (function (_super) {
  93103. __extends(DeviceOrientationCamera, _super);
  93104. /**
  93105. * Creates a new device orientation camera
  93106. * @param name The name of the camera
  93107. * @param position The start position camera
  93108. * @param scene The scene the camera belongs to
  93109. */
  93110. function DeviceOrientationCamera(name, position, scene) {
  93111. var _this = _super.call(this, name, position, scene) || this;
  93112. _this._quaternionCache = new BABYLON.Quaternion();
  93113. _this.inputs.addDeviceOrientation();
  93114. return _this;
  93115. }
  93116. /**
  93117. * Gets the current instance class name ("DeviceOrientationCamera").
  93118. * This helps avoiding instanceof at run time.
  93119. * @returns the class name
  93120. */
  93121. DeviceOrientationCamera.prototype.getClassName = function () {
  93122. return "DeviceOrientationCamera";
  93123. };
  93124. /**
  93125. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  93126. */
  93127. DeviceOrientationCamera.prototype._checkInputs = function () {
  93128. _super.prototype._checkInputs.call(this);
  93129. this._quaternionCache.copyFrom(this.rotationQuaternion);
  93130. if (this._initialQuaternion) {
  93131. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93132. }
  93133. };
  93134. /**
  93135. * Reset the camera to its default orientation on the specified axis only.
  93136. * @param axis The axis to reset
  93137. */
  93138. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  93139. var _this = this;
  93140. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  93141. //can only work if this camera has a rotation quaternion already.
  93142. if (!this.rotationQuaternion)
  93143. return;
  93144. if (!this._initialQuaternion) {
  93145. this._initialQuaternion = new BABYLON.Quaternion();
  93146. }
  93147. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  93148. ['x', 'y', 'z'].forEach(function (axisName) {
  93149. if (!axis[axisName]) {
  93150. _this._initialQuaternion[axisName] = 0;
  93151. }
  93152. else {
  93153. _this._initialQuaternion[axisName] *= -1;
  93154. }
  93155. });
  93156. this._initialQuaternion.normalize();
  93157. //force rotation update
  93158. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  93159. };
  93160. return DeviceOrientationCamera;
  93161. }(BABYLON.FreeCamera));
  93162. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  93163. })(BABYLON || (BABYLON = {}));
  93164. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  93165. var BABYLON;
  93166. (function (BABYLON) {
  93167. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93168. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  93169. });
  93170. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  93171. __extends(VRDeviceOrientationFreeCamera, _super);
  93172. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93173. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93174. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93175. var _this = _super.call(this, name, position, scene) || this;
  93176. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93177. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93178. return _this;
  93179. }
  93180. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  93181. return "VRDeviceOrientationFreeCamera";
  93182. };
  93183. return VRDeviceOrientationFreeCamera;
  93184. }(BABYLON.DeviceOrientationCamera));
  93185. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  93186. })(BABYLON || (BABYLON = {}));
  93187. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  93188. var BABYLON;
  93189. (function (BABYLON) {
  93190. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  93191. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  93192. });
  93193. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  93194. __extends(VRDeviceOrientationArcRotateCamera, _super);
  93195. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  93196. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93197. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93198. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93199. vrCameraMetrics.compensateDistortion = compensateDistortion;
  93200. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  93201. _this.inputs.addVRDeviceOrientation();
  93202. return _this;
  93203. }
  93204. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  93205. return "VRDeviceOrientationArcRotateCamera";
  93206. };
  93207. return VRDeviceOrientationArcRotateCamera;
  93208. }(BABYLON.ArcRotateCamera));
  93209. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  93210. })(BABYLON || (BABYLON = {}));
  93211. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  93212. var BABYLON;
  93213. (function (BABYLON) {
  93214. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  93215. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  93216. });
  93217. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  93218. __extends(VRDeviceOrientationGamepadCamera, _super);
  93219. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  93220. if (compensateDistortion === void 0) { compensateDistortion = true; }
  93221. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  93222. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  93223. _this.inputs.addGamepad();
  93224. return _this;
  93225. }
  93226. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  93227. return "VRDeviceOrientationGamepadCamera";
  93228. };
  93229. return VRDeviceOrientationGamepadCamera;
  93230. }(BABYLON.VRDeviceOrientationFreeCamera));
  93231. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  93232. })(BABYLON || (BABYLON = {}));
  93233. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  93234. var BABYLON;
  93235. (function (BABYLON) {
  93236. var VRExperienceHelperGazer = /** @class */ (function () {
  93237. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  93238. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  93239. this.scene = scene;
  93240. this._pointerDownOnMeshAsked = false;
  93241. this._isActionableMesh = false;
  93242. this._teleportationRequestInitiated = false;
  93243. this._teleportationBackRequestInitiated = false;
  93244. this._rotationRightAsked = false;
  93245. this._rotationLeftAsked = false;
  93246. this._dpadPressed = true;
  93247. this._activePointer = false;
  93248. this._id = VRExperienceHelperGazer._idCounter++;
  93249. // Gaze tracker
  93250. if (!gazeTrackerToClone) {
  93251. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  93252. this._gazeTracker.bakeCurrentTransformIntoVertices();
  93253. this._gazeTracker.isPickable = false;
  93254. this._gazeTracker.isVisible = false;
  93255. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  93256. targetMat.specularColor = BABYLON.Color3.Black();
  93257. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93258. targetMat.backFaceCulling = false;
  93259. this._gazeTracker.material = targetMat;
  93260. }
  93261. else {
  93262. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  93263. }
  93264. }
  93265. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  93266. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  93267. };
  93268. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  93269. this._pointerDownOnMeshAsked = true;
  93270. if (this._currentHit) {
  93271. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  93272. }
  93273. };
  93274. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  93275. if (this._currentHit) {
  93276. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  93277. }
  93278. this._pointerDownOnMeshAsked = false;
  93279. };
  93280. VRExperienceHelperGazer.prototype._activatePointer = function () {
  93281. this._activePointer = true;
  93282. };
  93283. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  93284. this._activePointer = false;
  93285. };
  93286. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  93287. if (distance === void 0) { distance = 100; }
  93288. };
  93289. VRExperienceHelperGazer.prototype.dispose = function () {
  93290. this._interactionsEnabled = false;
  93291. this._teleportationEnabled = false;
  93292. if (this._gazeTracker) {
  93293. this._gazeTracker.dispose();
  93294. }
  93295. };
  93296. VRExperienceHelperGazer._idCounter = 0;
  93297. return VRExperienceHelperGazer;
  93298. }());
  93299. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  93300. __extends(VRExperienceHelperControllerGazer, _super);
  93301. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  93302. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  93303. _this.webVRController = webVRController;
  93304. // Laser pointer
  93305. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  93306. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  93307. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  93308. laserPointerMaterial.alpha = 0.6;
  93309. _this._laserPointer.material = laserPointerMaterial;
  93310. _this._laserPointer.rotation.x = Math.PI / 2;
  93311. _this._laserPointer.position.z = -0.5;
  93312. _this._laserPointer.isVisible = false;
  93313. _this._laserPointer.isPickable = false;
  93314. if (!webVRController.mesh) {
  93315. // Create an empty mesh that is used prior to loading the high quality model
  93316. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  93317. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  93318. preloadPointerPose.rotation.x = -0.7;
  93319. preloadMesh.addChild(preloadPointerPose);
  93320. webVRController.attachToMesh(preloadMesh);
  93321. }
  93322. _this._setLaserPointerParent(webVRController.mesh);
  93323. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  93324. _this._setLaserPointerParent(mesh);
  93325. });
  93326. return _this;
  93327. }
  93328. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  93329. return this.webVRController.getForwardRay(length);
  93330. };
  93331. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  93332. _super.prototype._activatePointer.call(this);
  93333. this._laserPointer.isVisible = true;
  93334. };
  93335. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  93336. _super.prototype._deactivatePointer.call(this);
  93337. this._laserPointer.isVisible = false;
  93338. };
  93339. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  93340. this._laserPointer.material.emissiveColor = color;
  93341. };
  93342. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  93343. var makeNotPick = function (root) {
  93344. root.isPickable = false;
  93345. root.getChildMeshes().forEach(function (c) {
  93346. makeNotPick(c);
  93347. });
  93348. };
  93349. makeNotPick(mesh);
  93350. var childMeshes = mesh.getChildMeshes();
  93351. this.webVRController._pointingPoseNode = null;
  93352. for (var i = 0; i < childMeshes.length; i++) {
  93353. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  93354. mesh = childMeshes[i];
  93355. this.webVRController._pointingPoseNode = mesh;
  93356. break;
  93357. }
  93358. }
  93359. this._laserPointer.parent = mesh;
  93360. };
  93361. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  93362. if (distance === void 0) { distance = 100; }
  93363. this._laserPointer.scaling.y = distance;
  93364. this._laserPointer.position.z = -distance / 2;
  93365. };
  93366. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  93367. _super.prototype.dispose.call(this);
  93368. this._laserPointer.dispose();
  93369. if (this._meshAttachedObserver) {
  93370. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  93371. }
  93372. };
  93373. return VRExperienceHelperControllerGazer;
  93374. }(VRExperienceHelperGazer));
  93375. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  93376. __extends(VRExperienceHelperCameraGazer, _super);
  93377. function VRExperienceHelperCameraGazer(getCamera, scene) {
  93378. var _this = _super.call(this, scene) || this;
  93379. _this.getCamera = getCamera;
  93380. return _this;
  93381. }
  93382. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  93383. var camera = this.getCamera();
  93384. if (camera) {
  93385. return camera.getForwardRay(length);
  93386. }
  93387. else {
  93388. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  93389. }
  93390. };
  93391. return VRExperienceHelperCameraGazer;
  93392. }(VRExperienceHelperGazer));
  93393. /**
  93394. * Helps to quickly add VR support to an existing scene.
  93395. * See http://doc.babylonjs.com/how_to/webvr_helper
  93396. */
  93397. var VRExperienceHelper = /** @class */ (function () {
  93398. /**
  93399. * Instantiates a VRExperienceHelper.
  93400. * Helps to quickly add VR support to an existing scene.
  93401. * @param scene The scene the VRExperienceHelper belongs to.
  93402. * @param webVROptions Options to modify the vr experience helper's behavior.
  93403. */
  93404. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  93405. if (webVROptions === void 0) { webVROptions = {}; }
  93406. var _this = this;
  93407. this.webVROptions = webVROptions;
  93408. // Can the system support WebVR, even if a headset isn't plugged in?
  93409. this._webVRsupported = false;
  93410. // If WebVR is supported, is a headset plugged in and are we ready to present?
  93411. this._webVRready = false;
  93412. // Are we waiting for the requestPresent callback to complete?
  93413. this._webVRrequesting = false;
  93414. // Are we presenting to the headset right now?
  93415. this._webVRpresenting = false;
  93416. // Are we presenting in the fullscreen fallback?
  93417. this._fullscreenVRpresenting = false;
  93418. /**
  93419. * Observable raised when entering VR.
  93420. */
  93421. this.onEnteringVRObservable = new BABYLON.Observable();
  93422. /**
  93423. * Observable raised when exiting VR.
  93424. */
  93425. this.onExitingVRObservable = new BABYLON.Observable();
  93426. /**
  93427. * Observable raised when controller mesh is loaded.
  93428. */
  93429. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  93430. this._useCustomVRButton = false;
  93431. this._teleportationRequested = false;
  93432. this._teleportActive = false;
  93433. this._floorMeshesCollection = [];
  93434. this._rotationAllowed = true;
  93435. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  93436. this._isDefaultTeleportationTarget = true;
  93437. this._teleportationFillColor = "#444444";
  93438. this._teleportationBorderColor = "#FFFFFF";
  93439. this._rotationAngle = 0;
  93440. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  93441. this._padSensibilityUp = 0.65;
  93442. this._padSensibilityDown = 0.35;
  93443. this.leftController = null;
  93444. this.rightController = null;
  93445. /**
  93446. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  93447. */
  93448. this.onNewMeshSelected = new BABYLON.Observable();
  93449. /**
  93450. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  93451. */
  93452. this.onNewMeshPicked = new BABYLON.Observable();
  93453. /**
  93454. * Observable raised before camera teleportation
  93455. */
  93456. this.onBeforeCameraTeleport = new BABYLON.Observable();
  93457. /**
  93458. * Observable raised after camera teleportation
  93459. */
  93460. this.onAfterCameraTeleport = new BABYLON.Observable();
  93461. /**
  93462. * Observable raised when current selected mesh gets unselected
  93463. */
  93464. this.onSelectedMeshUnselected = new BABYLON.Observable();
  93465. /**
  93466. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  93467. */
  93468. this.teleportationEnabled = true;
  93469. this._teleportationInitialized = false;
  93470. this._interactionsEnabled = false;
  93471. this._interactionsRequested = false;
  93472. this._displayGaze = true;
  93473. this._displayLaserPointer = true;
  93474. this._onResize = function () {
  93475. _this.moveButtonToBottomRight();
  93476. if (_this._fullscreenVRpresenting && _this._webVRready) {
  93477. _this.exitVR();
  93478. }
  93479. };
  93480. this._onFullscreenChange = function () {
  93481. if (document.fullscreen !== undefined) {
  93482. _this._fullscreenVRpresenting = document.fullscreen;
  93483. }
  93484. else if (document.mozFullScreen !== undefined) {
  93485. _this._fullscreenVRpresenting = document.mozFullScreen;
  93486. }
  93487. else if (document.webkitIsFullScreen !== undefined) {
  93488. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  93489. }
  93490. else if (document.msIsFullScreen !== undefined) {
  93491. _this._fullscreenVRpresenting = document.msIsFullScreen;
  93492. }
  93493. else if (document.msFullscreenElement !== undefined) {
  93494. _this._fullscreenVRpresenting = document.msFullscreenElement;
  93495. }
  93496. if (!_this._fullscreenVRpresenting && _this._canvas) {
  93497. _this.exitVR();
  93498. if (!_this._useCustomVRButton) {
  93499. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  93500. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  93501. }
  93502. }
  93503. };
  93504. this.beforeRender = function () {
  93505. if (_this.leftController && _this.leftController._activePointer) {
  93506. _this._castRayAndSelectObject(_this.leftController);
  93507. }
  93508. if (_this.rightController && _this.rightController._activePointer) {
  93509. _this._castRayAndSelectObject(_this.rightController);
  93510. }
  93511. if (_this._noControllerIsActive) {
  93512. _this._castRayAndSelectObject(_this._cameraGazer);
  93513. }
  93514. else {
  93515. _this._cameraGazer._gazeTracker.isVisible = false;
  93516. }
  93517. };
  93518. this._onNewGamepadConnected = function (gamepad) {
  93519. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  93520. if (gamepad.leftStick) {
  93521. gamepad.onleftstickchanged(function (stickValues) {
  93522. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  93523. // Listening to classic/xbox gamepad only if no VR controller is active
  93524. if ((!_this.leftController && !_this.rightController) ||
  93525. ((_this.leftController && !_this.leftController._activePointer) &&
  93526. (_this.rightController && !_this.rightController._activePointer))) {
  93527. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  93528. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  93529. }
  93530. }
  93531. });
  93532. }
  93533. if (gamepad.rightStick) {
  93534. gamepad.onrightstickchanged(function (stickValues) {
  93535. if (_this._teleportationInitialized) {
  93536. _this._checkRotate(stickValues, _this._cameraGazer);
  93537. }
  93538. });
  93539. }
  93540. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  93541. gamepad.onbuttondown(function (buttonPressed) {
  93542. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93543. _this._cameraGazer._selectionPointerDown();
  93544. }
  93545. });
  93546. gamepad.onbuttonup(function (buttonPressed) {
  93547. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  93548. _this._cameraGazer._selectionPointerUp();
  93549. }
  93550. });
  93551. }
  93552. }
  93553. else {
  93554. var webVRController = gamepad;
  93555. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  93556. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  93557. _this.rightController = controller;
  93558. }
  93559. else {
  93560. _this.leftController = controller;
  93561. }
  93562. _this._tryEnableInteractionOnController(controller);
  93563. }
  93564. };
  93565. // 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
  93566. this._tryEnableInteractionOnController = function (controller) {
  93567. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  93568. _this._enableInteractionOnController(controller);
  93569. }
  93570. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  93571. _this._enableTeleportationOnController(controller);
  93572. }
  93573. };
  93574. this._onNewGamepadDisconnected = function (gamepad) {
  93575. if (gamepad instanceof BABYLON.WebVRController) {
  93576. if (gamepad.hand === "left" && _this.leftController != null) {
  93577. _this.leftController.dispose();
  93578. _this.leftController = null;
  93579. }
  93580. if (gamepad.hand === "right" && _this.rightController != null) {
  93581. _this.rightController.dispose();
  93582. _this.rightController = null;
  93583. }
  93584. }
  93585. };
  93586. this._workingVector = BABYLON.Vector3.Zero();
  93587. this._workingQuaternion = BABYLON.Quaternion.Identity();
  93588. this._workingMatrix = BABYLON.Matrix.Identity();
  93589. this._scene = scene;
  93590. this._canvas = scene.getEngine().getRenderingCanvas();
  93591. // Parse options
  93592. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  93593. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  93594. }
  93595. if (webVROptions.createDeviceOrientationCamera === undefined) {
  93596. webVROptions.createDeviceOrientationCamera = true;
  93597. }
  93598. if (webVROptions.laserToggle === undefined) {
  93599. webVROptions.laserToggle = true;
  93600. }
  93601. if (webVROptions.defaultHeight === undefined) {
  93602. webVROptions.defaultHeight = 1.7;
  93603. }
  93604. if (webVROptions.useCustomVRButton) {
  93605. this._useCustomVRButton = true;
  93606. if (webVROptions.customVRButton) {
  93607. this._btnVR = webVROptions.customVRButton;
  93608. }
  93609. }
  93610. if (webVROptions.rayLength) {
  93611. this._rayLength = webVROptions.rayLength;
  93612. }
  93613. this._defaultHeight = webVROptions.defaultHeight;
  93614. if (webVROptions.positionScale) {
  93615. this._rayLength *= webVROptions.positionScale;
  93616. this._defaultHeight *= webVROptions.positionScale;
  93617. }
  93618. // Set position
  93619. if (this._scene.activeCamera) {
  93620. this._position = this._scene.activeCamera.position.clone();
  93621. }
  93622. else {
  93623. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  93624. }
  93625. // Set non-vr camera
  93626. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  93627. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  93628. // Copy data from existing camera
  93629. if (this._scene.activeCamera) {
  93630. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93631. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  93632. // Set rotation from previous camera
  93633. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  93634. var targetCamera = this._scene.activeCamera;
  93635. if (targetCamera.rotationQuaternion) {
  93636. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  93637. }
  93638. else {
  93639. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  93640. }
  93641. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  93642. }
  93643. }
  93644. this._scene.activeCamera = this._deviceOrientationCamera;
  93645. if (this._canvas) {
  93646. this._scene.activeCamera.attachControl(this._canvas);
  93647. }
  93648. }
  93649. else {
  93650. this._existingCamera = this._scene.activeCamera;
  93651. }
  93652. // Create VR cameras
  93653. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93654. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  93655. }
  93656. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  93657. this._webVRCamera.useStandingMatrix();
  93658. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  93659. // Create default button
  93660. if (!this._useCustomVRButton) {
  93661. this._btnVR = document.createElement("BUTTON");
  93662. this._btnVR.className = "babylonVRicon";
  93663. this._btnVR.id = "babylonVRiconbtn";
  93664. this._btnVR.title = "Click to switch to VR";
  93665. 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) }";
  93666. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  93667. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  93668. // css += ".babylonVRicon.vrdisplaysupported { }";
  93669. // css += ".babylonVRicon.vrdisplayready { }";
  93670. // css += ".babylonVRicon.vrdisplayrequesting { }";
  93671. var style = document.createElement('style');
  93672. style.appendChild(document.createTextNode(css));
  93673. document.getElementsByTagName('head')[0].appendChild(style);
  93674. this.moveButtonToBottomRight();
  93675. }
  93676. // VR button click event
  93677. if (this._btnVR) {
  93678. this._btnVR.addEventListener("click", function () {
  93679. if (!_this.isInVRMode) {
  93680. _this.enterVR();
  93681. }
  93682. else {
  93683. _this.exitVR();
  93684. }
  93685. });
  93686. }
  93687. // Window events
  93688. window.addEventListener("resize", this._onResize);
  93689. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  93690. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  93691. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  93692. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  93693. document.onmsfullscreenchange = this._onFullscreenChange;
  93694. // Display vr button when headset is connected
  93695. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  93696. this.displayVRButton();
  93697. }
  93698. else {
  93699. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  93700. if (e.vrDisplay) {
  93701. _this.displayVRButton();
  93702. }
  93703. });
  93704. }
  93705. // Exiting VR mode using 'ESC' key on desktop
  93706. this._onKeyDown = function (event) {
  93707. if (event.keyCode === 27 && _this.isInVRMode) {
  93708. _this.exitVR();
  93709. }
  93710. };
  93711. document.addEventListener("keydown", this._onKeyDown);
  93712. // Exiting VR mode double tapping the touch screen
  93713. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  93714. if (_this.isInVRMode) {
  93715. _this.exitVR();
  93716. if (_this._fullscreenVRpresenting) {
  93717. _this._scene.getEngine().switchFullscreen(true);
  93718. }
  93719. }
  93720. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  93721. // Listen for WebVR display changes
  93722. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  93723. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  93724. this._onVRRequestPresentStart = function () {
  93725. _this._webVRrequesting = true;
  93726. _this.updateButtonVisibility();
  93727. };
  93728. this._onVRRequestPresentComplete = function (success) {
  93729. _this._webVRrequesting = false;
  93730. _this.updateButtonVisibility();
  93731. };
  93732. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  93733. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  93734. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  93735. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93736. scene.onDisposeObservable.add(function () {
  93737. _this.dispose();
  93738. });
  93739. // Gamepad connection events
  93740. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  93741. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  93742. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  93743. this.updateButtonVisibility();
  93744. //create easing functions
  93745. this._circleEase = new BABYLON.CircleEase();
  93746. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93747. if (this.webVROptions.floorMeshes) {
  93748. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  93749. }
  93750. }
  93751. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  93752. /** Return this.onEnteringVRObservable
  93753. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  93754. */
  93755. get: function () {
  93756. return this.onEnteringVRObservable;
  93757. },
  93758. enumerable: true,
  93759. configurable: true
  93760. });
  93761. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  93762. /** Return this.onExitingVRObservable
  93763. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  93764. */
  93765. get: function () {
  93766. return this.onExitingVRObservable;
  93767. },
  93768. enumerable: true,
  93769. configurable: true
  93770. });
  93771. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  93772. /** Return this.onControllerMeshLoadedObservable
  93773. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  93774. */
  93775. get: function () {
  93776. return this.onControllerMeshLoadedObservable;
  93777. },
  93778. enumerable: true,
  93779. configurable: true
  93780. });
  93781. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  93782. /**
  93783. * The mesh used to display where the user is going to teleport.
  93784. */
  93785. get: function () {
  93786. return this._teleportationTarget;
  93787. },
  93788. /**
  93789. * Sets the mesh to be used to display where the user is going to teleport.
  93790. */
  93791. set: function (value) {
  93792. if (value) {
  93793. value.name = "teleportationTarget";
  93794. this._isDefaultTeleportationTarget = false;
  93795. this._teleportationTarget = value;
  93796. }
  93797. },
  93798. enumerable: true,
  93799. configurable: true
  93800. });
  93801. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  93802. /**
  93803. * The mesh used to display where the user is selecting,
  93804. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  93805. * See http://doc.babylonjs.com/resources/baking_transformations
  93806. */
  93807. get: function () {
  93808. return this._cameraGazer._gazeTracker;
  93809. },
  93810. set: function (value) {
  93811. if (value) {
  93812. this._cameraGazer._gazeTracker = value;
  93813. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  93814. this._cameraGazer._gazeTracker.isPickable = false;
  93815. this._cameraGazer._gazeTracker.isVisible = false;
  93816. this._cameraGazer._gazeTracker.name = "gazeTracker";
  93817. if (this.leftController) {
  93818. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93819. }
  93820. if (this.rightController) {
  93821. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  93822. }
  93823. }
  93824. },
  93825. enumerable: true,
  93826. configurable: true
  93827. });
  93828. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  93829. /**
  93830. * If the ray of the gaze should be displayed.
  93831. */
  93832. get: function () {
  93833. return this._displayGaze;
  93834. },
  93835. /**
  93836. * Sets if the ray of the gaze should be displayed.
  93837. */
  93838. set: function (value) {
  93839. this._displayGaze = value;
  93840. if (!value) {
  93841. this._cameraGazer._gazeTracker.isVisible = false;
  93842. if (this.leftController) {
  93843. this.leftController._gazeTracker.isVisible = false;
  93844. }
  93845. if (this.rightController) {
  93846. this.rightController._gazeTracker.isVisible = false;
  93847. }
  93848. }
  93849. },
  93850. enumerable: true,
  93851. configurable: true
  93852. });
  93853. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  93854. /**
  93855. * If the ray of the LaserPointer should be displayed.
  93856. */
  93857. get: function () {
  93858. return this._displayLaserPointer;
  93859. },
  93860. /**
  93861. * Sets if the ray of the LaserPointer should be displayed.
  93862. */
  93863. set: function (value) {
  93864. this._displayLaserPointer = value;
  93865. if (!value) {
  93866. if (this.rightController) {
  93867. this.rightController._deactivatePointer();
  93868. this.rightController._gazeTracker.isVisible = false;
  93869. }
  93870. if (this.leftController) {
  93871. this.leftController._deactivatePointer();
  93872. this.leftController._gazeTracker.isVisible = false;
  93873. }
  93874. }
  93875. else {
  93876. if (this.rightController) {
  93877. this.rightController._activatePointer();
  93878. }
  93879. if (this.leftController) {
  93880. this.leftController._activatePointer();
  93881. }
  93882. }
  93883. },
  93884. enumerable: true,
  93885. configurable: true
  93886. });
  93887. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93888. /**
  93889. * The deviceOrientationCamera used as the camera when not in VR.
  93890. */
  93891. get: function () {
  93892. return this._deviceOrientationCamera;
  93893. },
  93894. enumerable: true,
  93895. configurable: true
  93896. });
  93897. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93898. /**
  93899. * Based on the current WebVR support, returns the current VR camera used.
  93900. */
  93901. get: function () {
  93902. if (this._webVRready) {
  93903. return this._webVRCamera;
  93904. }
  93905. else {
  93906. return this._scene.activeCamera;
  93907. }
  93908. },
  93909. enumerable: true,
  93910. configurable: true
  93911. });
  93912. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93913. /**
  93914. * The webVRCamera which is used when in VR.
  93915. */
  93916. get: function () {
  93917. return this._webVRCamera;
  93918. },
  93919. enumerable: true,
  93920. configurable: true
  93921. });
  93922. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93923. /**
  93924. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93925. */
  93926. get: function () {
  93927. return this._vrDeviceOrientationCamera;
  93928. },
  93929. enumerable: true,
  93930. configurable: true
  93931. });
  93932. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93933. get: function () {
  93934. var result = this._cameraGazer._teleportationRequestInitiated
  93935. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93936. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93937. return result;
  93938. },
  93939. enumerable: true,
  93940. configurable: true
  93941. });
  93942. // Raised when one of the controller has loaded successfully its associated default mesh
  93943. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93944. if (this.leftController && this.leftController.webVRController == webVRController) {
  93945. if (webVRController.mesh) {
  93946. this.leftController._setLaserPointerParent(webVRController.mesh);
  93947. }
  93948. }
  93949. if (this.rightController && this.rightController.webVRController == webVRController) {
  93950. if (webVRController.mesh) {
  93951. this.rightController._setLaserPointerParent(webVRController.mesh);
  93952. }
  93953. }
  93954. try {
  93955. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93956. }
  93957. catch (err) {
  93958. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93959. }
  93960. };
  93961. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93962. /**
  93963. * Gets a value indicating if we are currently in VR mode.
  93964. */
  93965. get: function () {
  93966. return this._webVRpresenting || this._fullscreenVRpresenting;
  93967. },
  93968. enumerable: true,
  93969. configurable: true
  93970. });
  93971. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93972. var vrDisplay = this._scene.getEngine().getVRDevice();
  93973. if (vrDisplay) {
  93974. var wasPresenting = this._webVRpresenting;
  93975. // A VR display is connected
  93976. this._webVRpresenting = vrDisplay.isPresenting;
  93977. if (wasPresenting && !this._webVRpresenting)
  93978. this.exitVR();
  93979. }
  93980. else {
  93981. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93982. }
  93983. this.updateButtonVisibility();
  93984. };
  93985. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93986. this._webVRsupported = eventArgs.vrSupported;
  93987. this._webVRready = !!eventArgs.vrDisplay;
  93988. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93989. this.updateButtonVisibility();
  93990. };
  93991. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93992. if (this._canvas && !this._useCustomVRButton) {
  93993. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93994. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93995. }
  93996. };
  93997. VRExperienceHelper.prototype.displayVRButton = function () {
  93998. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93999. document.body.appendChild(this._btnVR);
  94000. this._btnVRDisplayed = true;
  94001. }
  94002. };
  94003. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  94004. if (!this._btnVR || this._useCustomVRButton) {
  94005. return;
  94006. }
  94007. this._btnVR.className = "babylonVRicon";
  94008. if (this.isInVRMode) {
  94009. this._btnVR.className += " vrdisplaypresenting";
  94010. }
  94011. else {
  94012. if (this._webVRready)
  94013. this._btnVR.className += " vrdisplayready";
  94014. if (this._webVRsupported)
  94015. this._btnVR.className += " vrdisplaysupported";
  94016. if (this._webVRrequesting)
  94017. this._btnVR.className += " vrdisplayrequesting";
  94018. }
  94019. };
  94020. /**
  94021. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  94022. * Otherwise, will use the fullscreen API.
  94023. */
  94024. VRExperienceHelper.prototype.enterVR = function () {
  94025. if (this.onEnteringVRObservable) {
  94026. try {
  94027. this.onEnteringVRObservable.notifyObservers(this);
  94028. }
  94029. catch (err) {
  94030. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  94031. }
  94032. }
  94033. if (this._scene.activeCamera) {
  94034. this._position = this._scene.activeCamera.position.clone();
  94035. // make sure that we return to the last active camera
  94036. this._existingCamera = this._scene.activeCamera;
  94037. }
  94038. if (this._webVRrequesting)
  94039. return;
  94040. // If WebVR is supported and a headset is connected
  94041. if (this._webVRready) {
  94042. if (!this._webVRpresenting) {
  94043. this._webVRCamera.position = this._position;
  94044. this._scene.activeCamera = this._webVRCamera;
  94045. }
  94046. }
  94047. else if (this._vrDeviceOrientationCamera) {
  94048. this._vrDeviceOrientationCamera.position = this._position;
  94049. if (this._scene.activeCamera) {
  94050. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  94051. }
  94052. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  94053. this._scene.getEngine().switchFullscreen(true);
  94054. this.updateButtonVisibility();
  94055. }
  94056. if (this._scene.activeCamera && this._canvas) {
  94057. this._scene.activeCamera.attachControl(this._canvas);
  94058. }
  94059. if (this._interactionsEnabled) {
  94060. this._scene.registerBeforeRender(this.beforeRender);
  94061. }
  94062. };
  94063. /**
  94064. * Attempt to exit VR, or fullscreen.
  94065. */
  94066. VRExperienceHelper.prototype.exitVR = function () {
  94067. if (this.onExitingVRObservable) {
  94068. try {
  94069. this.onExitingVRObservable.notifyObservers(this);
  94070. }
  94071. catch (err) {
  94072. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  94073. }
  94074. }
  94075. if (this._webVRpresenting) {
  94076. this._scene.getEngine().disableVR();
  94077. }
  94078. if (this._scene.activeCamera) {
  94079. this._position = this._scene.activeCamera.position.clone();
  94080. }
  94081. if (this._deviceOrientationCamera) {
  94082. this._deviceOrientationCamera.position = this._position;
  94083. this._scene.activeCamera = this._deviceOrientationCamera;
  94084. if (this._canvas) {
  94085. this._scene.activeCamera.attachControl(this._canvas);
  94086. }
  94087. }
  94088. else if (this._existingCamera) {
  94089. this._existingCamera.position = this._position;
  94090. this._scene.activeCamera = this._existingCamera;
  94091. }
  94092. this.updateButtonVisibility();
  94093. if (this._interactionsEnabled) {
  94094. this._scene.unregisterBeforeRender(this.beforeRender);
  94095. }
  94096. // resize to update width and height when exiting vr exits fullscreen
  94097. this._scene.getEngine().resize();
  94098. };
  94099. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  94100. /**
  94101. * The position of the vr experience helper.
  94102. */
  94103. get: function () {
  94104. return this._position;
  94105. },
  94106. /**
  94107. * Sets the position of the vr experience helper.
  94108. */
  94109. set: function (value) {
  94110. this._position = value;
  94111. if (this._scene.activeCamera) {
  94112. this._scene.activeCamera.position = value;
  94113. }
  94114. },
  94115. enumerable: true,
  94116. configurable: true
  94117. });
  94118. /**
  94119. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  94120. */
  94121. VRExperienceHelper.prototype.enableInteractions = function () {
  94122. var _this = this;
  94123. if (!this._interactionsEnabled) {
  94124. this._interactionsRequested = true;
  94125. if (this.leftController) {
  94126. this._enableInteractionOnController(this.leftController);
  94127. }
  94128. if (this.rightController) {
  94129. this._enableInteractionOnController(this.rightController);
  94130. }
  94131. this.raySelectionPredicate = function (mesh) {
  94132. return mesh.isVisible && mesh.isPickable;
  94133. };
  94134. this.meshSelectionPredicate = function (mesh) {
  94135. return true;
  94136. };
  94137. this._raySelectionPredicate = function (mesh) {
  94138. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  94139. && mesh.name.indexOf("teleportationTarget") === -1
  94140. && mesh.name.indexOf("torusTeleportation") === -1)) {
  94141. return _this.raySelectionPredicate(mesh);
  94142. }
  94143. return false;
  94144. };
  94145. this._interactionsEnabled = true;
  94146. }
  94147. };
  94148. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  94149. get: function () {
  94150. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  94151. },
  94152. enumerable: true,
  94153. configurable: true
  94154. });
  94155. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  94156. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  94157. if (this._floorMeshesCollection[i].id === mesh.id) {
  94158. return true;
  94159. }
  94160. }
  94161. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  94162. return true;
  94163. }
  94164. return false;
  94165. };
  94166. /**
  94167. * Adds a floor mesh to be used for teleportation.
  94168. * @param floorMesh the mesh to be used for teleportation.
  94169. */
  94170. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  94171. if (!this._floorMeshesCollection) {
  94172. return;
  94173. }
  94174. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  94175. return;
  94176. }
  94177. this._floorMeshesCollection.push(floorMesh);
  94178. };
  94179. /**
  94180. * Removes a floor mesh from being used for teleportation.
  94181. * @param floorMesh the mesh to be removed.
  94182. */
  94183. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  94184. if (!this._floorMeshesCollection) {
  94185. return;
  94186. }
  94187. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  94188. if (meshIndex !== -1) {
  94189. this._floorMeshesCollection.splice(meshIndex, 1);
  94190. }
  94191. };
  94192. /**
  94193. * Enables interactions and teleportation using the VR controllers and gaze.
  94194. * @param vrTeleportationOptions options to modify teleportation behavior.
  94195. */
  94196. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  94197. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  94198. if (!this._teleportationInitialized) {
  94199. this._teleportationRequested = true;
  94200. this.enableInteractions();
  94201. if (vrTeleportationOptions.floorMeshName) {
  94202. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  94203. }
  94204. if (vrTeleportationOptions.floorMeshes) {
  94205. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  94206. }
  94207. if (this.leftController != null) {
  94208. this._enableTeleportationOnController(this.leftController);
  94209. }
  94210. if (this.rightController != null) {
  94211. this._enableTeleportationOnController(this.rightController);
  94212. }
  94213. // Creates an image processing post process for the vignette not relying
  94214. // on the main scene configuration for image processing to reduce setup and spaces
  94215. // (gamma/linear) conflicts.
  94216. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  94217. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  94218. imageProcessingConfiguration.vignetteEnabled = true;
  94219. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  94220. this._webVRCamera.detachPostProcess(this._postProcessMove);
  94221. this._teleportationInitialized = true;
  94222. if (this._isDefaultTeleportationTarget) {
  94223. this._createTeleportationCircles();
  94224. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  94225. }
  94226. }
  94227. };
  94228. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  94229. var _this = this;
  94230. var controllerMesh = controller.webVRController.mesh;
  94231. if (controllerMesh) {
  94232. controller._interactionsEnabled = true;
  94233. controller._activatePointer();
  94234. if (this.webVROptions.laserToggle) {
  94235. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  94236. // Enabling / disabling laserPointer
  94237. if (_this._displayLaserPointer && stateObject.value === 1) {
  94238. if (controller._activePointer) {
  94239. controller._deactivatePointer();
  94240. }
  94241. else {
  94242. controller._activatePointer();
  94243. }
  94244. if (_this.displayGaze) {
  94245. controller._gazeTracker.isVisible = controller._activePointer;
  94246. }
  94247. }
  94248. });
  94249. }
  94250. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  94251. var gazer = controller;
  94252. if (_this._noControllerIsActive) {
  94253. gazer = _this._cameraGazer;
  94254. }
  94255. if (!gazer._pointerDownOnMeshAsked) {
  94256. if (stateObject.value > _this._padSensibilityUp) {
  94257. gazer._selectionPointerDown();
  94258. }
  94259. }
  94260. else if (stateObject.value < _this._padSensibilityDown) {
  94261. gazer._selectionPointerUp();
  94262. }
  94263. });
  94264. }
  94265. };
  94266. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  94267. // Dont teleport if another gaze already requested teleportation
  94268. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  94269. return;
  94270. }
  94271. if (!gazer._teleportationRequestInitiated) {
  94272. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  94273. gazer._activatePointer();
  94274. gazer._teleportationRequestInitiated = true;
  94275. }
  94276. }
  94277. else {
  94278. // Listening to the proper controller values changes to confirm teleportation
  94279. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  94280. if (this._teleportActive) {
  94281. this._teleportCamera(this._haloCenter);
  94282. }
  94283. gazer._teleportationRequestInitiated = false;
  94284. }
  94285. }
  94286. };
  94287. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  94288. // Only rotate when user is not currently selecting a teleportation location
  94289. if (gazer._teleportationRequestInitiated) {
  94290. return;
  94291. }
  94292. if (!gazer._rotationLeftAsked) {
  94293. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  94294. gazer._rotationLeftAsked = true;
  94295. if (this._rotationAllowed) {
  94296. this._rotateCamera(false);
  94297. }
  94298. }
  94299. }
  94300. else {
  94301. if (stateObject.x > -this._padSensibilityDown) {
  94302. gazer._rotationLeftAsked = false;
  94303. }
  94304. }
  94305. if (!gazer._rotationRightAsked) {
  94306. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  94307. gazer._rotationRightAsked = true;
  94308. if (this._rotationAllowed) {
  94309. this._rotateCamera(true);
  94310. }
  94311. }
  94312. }
  94313. else {
  94314. if (stateObject.x < this._padSensibilityDown) {
  94315. gazer._rotationRightAsked = false;
  94316. }
  94317. }
  94318. };
  94319. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  94320. // Only teleport backwards when user is not currently selecting a teleportation location
  94321. if (gazer._teleportationRequestInitiated) {
  94322. return;
  94323. }
  94324. // Teleport backwards
  94325. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  94326. if (!gazer._teleportationBackRequestInitiated) {
  94327. if (!this.currentVRCamera) {
  94328. return;
  94329. }
  94330. // Get rotation and position of the current camera
  94331. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  94332. var position = this.currentVRCamera.position;
  94333. // If the camera has device position, use that instead
  94334. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  94335. rotation = this.currentVRCamera.deviceRotationQuaternion;
  94336. position = this.currentVRCamera.devicePosition;
  94337. }
  94338. // Get matrix with only the y rotation of the device rotation
  94339. rotation.toEulerAnglesToRef(this._workingVector);
  94340. this._workingVector.z = 0;
  94341. this._workingVector.x = 0;
  94342. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  94343. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  94344. // Rotate backwards ray by device rotation to cast at the ground behind the user
  94345. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  94346. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  94347. var ray = new BABYLON.Ray(position, this._workingVector);
  94348. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94349. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  94350. this._teleportCamera(hit.pickedPoint);
  94351. }
  94352. gazer._teleportationBackRequestInitiated = true;
  94353. }
  94354. }
  94355. else {
  94356. gazer._teleportationBackRequestInitiated = false;
  94357. }
  94358. };
  94359. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  94360. var _this = this;
  94361. var controllerMesh = controller.webVRController.mesh;
  94362. if (controllerMesh) {
  94363. if (!controller._interactionsEnabled) {
  94364. this._enableInteractionOnController(controller);
  94365. }
  94366. controller._interactionsEnabled = true;
  94367. controller._teleportationEnabled = true;
  94368. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94369. controller._dpadPressed = false;
  94370. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  94371. controller._dpadPressed = stateObject.pressed;
  94372. if (!controller._dpadPressed) {
  94373. controller._rotationLeftAsked = false;
  94374. controller._rotationRightAsked = false;
  94375. controller._teleportationBackRequestInitiated = false;
  94376. }
  94377. });
  94378. }
  94379. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  94380. if (_this.teleportationEnabled) {
  94381. _this._checkTeleportBackwards(stateObject, controller);
  94382. _this._checkTeleportWithRay(stateObject, controller);
  94383. }
  94384. _this._checkRotate(stateObject, controller);
  94385. });
  94386. }
  94387. };
  94388. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  94389. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  94390. this._teleportationTarget.isPickable = false;
  94391. var length = 512;
  94392. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  94393. dynamicTexture.hasAlpha = true;
  94394. var context = dynamicTexture.getContext();
  94395. var centerX = length / 2;
  94396. var centerY = length / 2;
  94397. var radius = 200;
  94398. context.beginPath();
  94399. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  94400. context.fillStyle = this._teleportationFillColor;
  94401. context.fill();
  94402. context.lineWidth = 10;
  94403. context.strokeStyle = this._teleportationBorderColor;
  94404. context.stroke();
  94405. context.closePath();
  94406. dynamicTexture.update();
  94407. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  94408. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  94409. this._teleportationTarget.material = teleportationCircleMaterial;
  94410. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  94411. torus.isPickable = false;
  94412. torus.parent = this._teleportationTarget;
  94413. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  94414. var keys = [];
  94415. keys.push({
  94416. frame: 0,
  94417. value: 0
  94418. });
  94419. keys.push({
  94420. frame: 30,
  94421. value: 0.4
  94422. });
  94423. keys.push({
  94424. frame: 60,
  94425. value: 0
  94426. });
  94427. animationInnerCircle.setKeys(keys);
  94428. var easingFunction = new BABYLON.SineEase();
  94429. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  94430. animationInnerCircle.setEasingFunction(easingFunction);
  94431. torus.animations = [];
  94432. torus.animations.push(animationInnerCircle);
  94433. this._scene.beginAnimation(torus, 0, 60, true);
  94434. this._hideTeleportationTarget();
  94435. };
  94436. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  94437. this._teleportActive = true;
  94438. if (this._teleportationInitialized) {
  94439. this._teleportationTarget.isVisible = true;
  94440. if (this._isDefaultTeleportationTarget) {
  94441. this._teleportationTarget.getChildren()[0].isVisible = true;
  94442. }
  94443. }
  94444. };
  94445. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  94446. this._teleportActive = false;
  94447. if (this._teleportationInitialized) {
  94448. this._teleportationTarget.isVisible = false;
  94449. if (this._isDefaultTeleportationTarget) {
  94450. this._teleportationTarget.getChildren()[0].isVisible = false;
  94451. }
  94452. }
  94453. };
  94454. VRExperienceHelper.prototype._rotateCamera = function (right) {
  94455. var _this = this;
  94456. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94457. return;
  94458. }
  94459. if (right) {
  94460. this._rotationAngle++;
  94461. }
  94462. else {
  94463. this._rotationAngle--;
  94464. }
  94465. this.currentVRCamera.animations = [];
  94466. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  94467. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94468. var animationRotationKeys = [];
  94469. animationRotationKeys.push({
  94470. frame: 0,
  94471. value: this.currentVRCamera.rotationQuaternion
  94472. });
  94473. animationRotationKeys.push({
  94474. frame: 6,
  94475. value: target
  94476. });
  94477. animationRotation.setKeys(animationRotationKeys);
  94478. animationRotation.setEasingFunction(this._circleEase);
  94479. this.currentVRCamera.animations.push(animationRotation);
  94480. this._postProcessMove.animations = [];
  94481. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94482. var vignetteWeightKeys = [];
  94483. vignetteWeightKeys.push({
  94484. frame: 0,
  94485. value: 0
  94486. });
  94487. vignetteWeightKeys.push({
  94488. frame: 3,
  94489. value: 4
  94490. });
  94491. vignetteWeightKeys.push({
  94492. frame: 6,
  94493. value: 0
  94494. });
  94495. animationPP.setKeys(vignetteWeightKeys);
  94496. animationPP.setEasingFunction(this._circleEase);
  94497. this._postProcessMove.animations.push(animationPP);
  94498. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94499. var vignetteStretchKeys = [];
  94500. vignetteStretchKeys.push({
  94501. frame: 0,
  94502. value: 0
  94503. });
  94504. vignetteStretchKeys.push({
  94505. frame: 3,
  94506. value: 10
  94507. });
  94508. vignetteStretchKeys.push({
  94509. frame: 6,
  94510. value: 0
  94511. });
  94512. animationPP2.setKeys(vignetteStretchKeys);
  94513. animationPP2.setEasingFunction(this._circleEase);
  94514. this._postProcessMove.animations.push(animationPP2);
  94515. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94516. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94517. this._postProcessMove.samples = 4;
  94518. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94519. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  94520. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94521. });
  94522. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  94523. };
  94524. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  94525. if (hit.pickedPoint) {
  94526. if (gazer._teleportationRequestInitiated) {
  94527. this._displayTeleportationTarget();
  94528. this._haloCenter.copyFrom(hit.pickedPoint);
  94529. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  94530. }
  94531. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  94532. if (pickNormal) {
  94533. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94534. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94535. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  94536. }
  94537. this._teleportationTarget.position.y += 0.1;
  94538. }
  94539. };
  94540. VRExperienceHelper.prototype._teleportCamera = function (location) {
  94541. var _this = this;
  94542. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94543. return;
  94544. }
  94545. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  94546. // offset of the headset from the anchor.
  94547. if (this.webVRCamera.leftCamera) {
  94548. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  94549. this._workingVector.subtractInPlace(this.webVRCamera.position);
  94550. location.subtractToRef(this._workingVector, this._workingVector);
  94551. }
  94552. else {
  94553. this._workingVector.copyFrom(location);
  94554. }
  94555. // Add height to account for user's height offset
  94556. if (this.isInVRMode) {
  94557. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  94558. }
  94559. else {
  94560. this._workingVector.y += this._defaultHeight;
  94561. }
  94562. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  94563. // Create animation from the camera's position to the new location
  94564. this.currentVRCamera.animations = [];
  94565. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94566. var animationCameraTeleportationKeys = [{
  94567. frame: 0,
  94568. value: this.currentVRCamera.position
  94569. },
  94570. {
  94571. frame: 11,
  94572. value: this._workingVector
  94573. }
  94574. ];
  94575. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  94576. animationCameraTeleportation.setEasingFunction(this._circleEase);
  94577. this.currentVRCamera.animations.push(animationCameraTeleportation);
  94578. this._postProcessMove.animations = [];
  94579. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94580. var vignetteWeightKeys = [];
  94581. vignetteWeightKeys.push({
  94582. frame: 0,
  94583. value: 0
  94584. });
  94585. vignetteWeightKeys.push({
  94586. frame: 5,
  94587. value: 8
  94588. });
  94589. vignetteWeightKeys.push({
  94590. frame: 11,
  94591. value: 0
  94592. });
  94593. animationPP.setKeys(vignetteWeightKeys);
  94594. this._postProcessMove.animations.push(animationPP);
  94595. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  94596. var vignetteStretchKeys = [];
  94597. vignetteStretchKeys.push({
  94598. frame: 0,
  94599. value: 0
  94600. });
  94601. vignetteStretchKeys.push({
  94602. frame: 5,
  94603. value: 10
  94604. });
  94605. vignetteStretchKeys.push({
  94606. frame: 11,
  94607. value: 0
  94608. });
  94609. animationPP2.setKeys(vignetteStretchKeys);
  94610. this._postProcessMove.animations.push(animationPP2);
  94611. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  94612. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  94613. this._webVRCamera.attachPostProcess(this._postProcessMove);
  94614. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  94615. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  94616. });
  94617. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  94618. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  94619. });
  94620. this._hideTeleportationTarget();
  94621. };
  94622. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  94623. if (normal) {
  94624. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  94625. if (angle < Math.PI / 2) {
  94626. normal.scaleInPlace(-1);
  94627. }
  94628. }
  94629. return normal;
  94630. };
  94631. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  94632. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  94633. return;
  94634. }
  94635. var ray = gazer._getForwardRay(this._rayLength);
  94636. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  94637. if (hit) {
  94638. // Populate the contrllers mesh that can be used for drag/drop
  94639. if (gazer._laserPointer) {
  94640. hit.originMesh = gazer._laserPointer.parent;
  94641. }
  94642. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  94643. }
  94644. gazer._currentHit = hit;
  94645. // Moving the gazeTracker on the mesh face targetted
  94646. if (hit && hit.pickedPoint) {
  94647. if (this._displayGaze) {
  94648. var multiplier = 1;
  94649. gazer._gazeTracker.isVisible = true;
  94650. if (gazer._isActionableMesh) {
  94651. multiplier = 3;
  94652. }
  94653. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  94654. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  94655. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  94656. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  94657. // To avoid z-fighting
  94658. var deltaFighting = 0.002;
  94659. if (pickNormal) {
  94660. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  94661. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  94662. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  94663. }
  94664. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  94665. if (gazer._gazeTracker.position.x < 0) {
  94666. gazer._gazeTracker.position.x += deltaFighting;
  94667. }
  94668. else {
  94669. gazer._gazeTracker.position.x -= deltaFighting;
  94670. }
  94671. if (gazer._gazeTracker.position.y < 0) {
  94672. gazer._gazeTracker.position.y += deltaFighting;
  94673. }
  94674. else {
  94675. gazer._gazeTracker.position.y -= deltaFighting;
  94676. }
  94677. if (gazer._gazeTracker.position.z < 0) {
  94678. gazer._gazeTracker.position.z += deltaFighting;
  94679. }
  94680. else {
  94681. gazer._gazeTracker.position.z -= deltaFighting;
  94682. }
  94683. }
  94684. // Changing the size of the laser pointer based on the distance from the targetted point
  94685. gazer._updatePointerDistance(hit.distance);
  94686. }
  94687. else {
  94688. gazer._updatePointerDistance();
  94689. gazer._gazeTracker.isVisible = false;
  94690. }
  94691. if (hit && hit.pickedMesh) {
  94692. // The object selected is the floor, we're in a teleportation scenario
  94693. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  94694. // Moving the teleportation area to this targetted point
  94695. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  94696. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  94697. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94698. }
  94699. gazer._currentMeshSelected = null;
  94700. if (gazer._teleportationRequestInitiated) {
  94701. this._moveTeleportationSelectorTo(hit, gazer, ray);
  94702. }
  94703. return;
  94704. }
  94705. // If not, we're in a selection scenario
  94706. //this._teleportationAllowed = false;
  94707. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  94708. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  94709. this.onNewMeshPicked.notifyObservers(hit);
  94710. gazer._currentMeshSelected = hit.pickedMesh;
  94711. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  94712. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  94713. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  94714. gazer._isActionableMesh = true;
  94715. }
  94716. else {
  94717. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94718. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94719. gazer._isActionableMesh = false;
  94720. }
  94721. try {
  94722. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  94723. }
  94724. catch (err) {
  94725. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  94726. }
  94727. }
  94728. else {
  94729. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94730. gazer._currentMeshSelected = null;
  94731. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94732. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94733. }
  94734. }
  94735. }
  94736. else {
  94737. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  94738. gazer._currentMeshSelected = null;
  94739. //this._teleportationAllowed = false;
  94740. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94741. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  94742. }
  94743. };
  94744. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  94745. if (mesh) {
  94746. this.onSelectedMeshUnselected.notifyObservers(mesh);
  94747. }
  94748. };
  94749. /**
  94750. * Sets the color of the laser ray from the vr controllers.
  94751. * @param color new color for the ray.
  94752. */
  94753. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  94754. if (this.leftController) {
  94755. this.leftController._setLaserPointerColor(color);
  94756. }
  94757. if (this.rightController) {
  94758. this.rightController._setLaserPointerColor(color);
  94759. }
  94760. };
  94761. /**
  94762. * Sets the color of the ray from the vr headsets gaze.
  94763. * @param color new color for the ray.
  94764. */
  94765. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  94766. if (!this._cameraGazer._gazeTracker.material) {
  94767. return;
  94768. }
  94769. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  94770. if (this.leftController) {
  94771. this.leftController._gazeTracker.material.emissiveColor = color;
  94772. }
  94773. if (this.rightController) {
  94774. this.rightController._gazeTracker.material.emissiveColor = color;
  94775. }
  94776. };
  94777. /**
  94778. * Exits VR and disposes of the vr experience helper
  94779. */
  94780. VRExperienceHelper.prototype.dispose = function () {
  94781. if (this.isInVRMode) {
  94782. this.exitVR();
  94783. }
  94784. if (this._postProcessMove) {
  94785. this._postProcessMove.dispose();
  94786. }
  94787. if (this._webVRCamera) {
  94788. this._webVRCamera.dispose();
  94789. }
  94790. if (this._vrDeviceOrientationCamera) {
  94791. this._vrDeviceOrientationCamera.dispose();
  94792. }
  94793. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  94794. document.body.removeChild(this._btnVR);
  94795. }
  94796. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  94797. this._deviceOrientationCamera.dispose();
  94798. }
  94799. if (this._cameraGazer) {
  94800. this._cameraGazer.dispose();
  94801. }
  94802. if (this.leftController) {
  94803. this.leftController.dispose();
  94804. }
  94805. if (this.rightController) {
  94806. this.rightController.dispose();
  94807. }
  94808. if (this._teleportationTarget) {
  94809. this._teleportationTarget.dispose();
  94810. }
  94811. this._floorMeshesCollection = [];
  94812. document.removeEventListener("keydown", this._onKeyDown);
  94813. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94814. window.removeEventListener("resize", this._onResize);
  94815. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  94816. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  94817. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  94818. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  94819. document.onmsfullscreenchange = null;
  94820. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  94821. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  94822. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  94823. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  94824. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  94825. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  94826. this._scene.unregisterBeforeRender(this.beforeRender);
  94827. };
  94828. /**
  94829. * Gets the name of the VRExperienceHelper class
  94830. * @returns "VRExperienceHelper"
  94831. */
  94832. VRExperienceHelper.prototype.getClassName = function () {
  94833. return "VRExperienceHelper";
  94834. };
  94835. return VRExperienceHelper;
  94836. }());
  94837. BABYLON.VRExperienceHelper = VRExperienceHelper;
  94838. })(BABYLON || (BABYLON = {}));
  94839. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  94840. // Mainly based on these 2 articles :
  94841. // 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
  94842. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  94843. var BABYLON;
  94844. (function (BABYLON) {
  94845. /**
  94846. * Defines the potential axis of a Joystick
  94847. */
  94848. var JoystickAxis;
  94849. (function (JoystickAxis) {
  94850. /** X axis */
  94851. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  94852. /** Y axis */
  94853. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  94854. /** Z axis */
  94855. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  94856. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  94857. /**
  94858. * Class used to define virtual joystick (used in touch mode)
  94859. */
  94860. var VirtualJoystick = /** @class */ (function () {
  94861. /**
  94862. * Creates a new virtual joystick
  94863. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94864. */
  94865. function VirtualJoystick(leftJoystick) {
  94866. var _this = this;
  94867. if (leftJoystick) {
  94868. this._leftJoystick = true;
  94869. }
  94870. else {
  94871. this._leftJoystick = false;
  94872. }
  94873. VirtualJoystick._globalJoystickIndex++;
  94874. // By default left & right arrow keys are moving the X
  94875. // and up & down keys are moving the Y
  94876. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94877. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94878. this.reverseLeftRight = false;
  94879. this.reverseUpDown = false;
  94880. // collections of pointers
  94881. this._touches = new BABYLON.StringDictionary();
  94882. this.deltaPosition = BABYLON.Vector3.Zero();
  94883. this._joystickSensibility = 25;
  94884. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94885. this._onResize = function (evt) {
  94886. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94887. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94888. if (VirtualJoystick.vjCanvas) {
  94889. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94890. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94891. }
  94892. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94893. };
  94894. // injecting a canvas element on top of the canvas 3D game
  94895. if (!VirtualJoystick.vjCanvas) {
  94896. window.addEventListener("resize", this._onResize, false);
  94897. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94898. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94899. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94900. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94901. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94902. VirtualJoystick.vjCanvas.style.width = "100%";
  94903. VirtualJoystick.vjCanvas.style.height = "100%";
  94904. VirtualJoystick.vjCanvas.style.position = "absolute";
  94905. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94906. VirtualJoystick.vjCanvas.style.top = "0px";
  94907. VirtualJoystick.vjCanvas.style.left = "0px";
  94908. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94909. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94910. // Support for jQuery PEP polyfill
  94911. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94912. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94913. if (!context) {
  94914. throw new Error("Unable to create canvas for virtual joystick");
  94915. }
  94916. VirtualJoystick.vjCanvasContext = context;
  94917. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94918. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94919. document.body.appendChild(VirtualJoystick.vjCanvas);
  94920. }
  94921. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94922. this.pressed = false;
  94923. // default joystick color
  94924. this._joystickColor = "cyan";
  94925. this._joystickPointerID = -1;
  94926. // current joystick position
  94927. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94928. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94929. // origin joystick position
  94930. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94931. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94932. this._onPointerDownHandlerRef = function (evt) {
  94933. _this._onPointerDown(evt);
  94934. };
  94935. this._onPointerMoveHandlerRef = function (evt) {
  94936. _this._onPointerMove(evt);
  94937. };
  94938. this._onPointerUpHandlerRef = function (evt) {
  94939. _this._onPointerUp(evt);
  94940. };
  94941. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94942. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94943. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94944. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94945. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94946. evt.preventDefault(); // Disables system menu
  94947. }, false);
  94948. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94949. }
  94950. /**
  94951. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94952. * @param newJoystickSensibility defines the new sensibility
  94953. */
  94954. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94955. this._joystickSensibility = newJoystickSensibility;
  94956. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94957. };
  94958. VirtualJoystick.prototype._onPointerDown = function (e) {
  94959. var positionOnScreenCondition;
  94960. e.preventDefault();
  94961. if (this._leftJoystick === true) {
  94962. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94963. }
  94964. else {
  94965. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94966. }
  94967. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94968. // First contact will be dedicated to the virtual joystick
  94969. this._joystickPointerID = e.pointerId;
  94970. this._joystickPointerStartPos.x = e.clientX;
  94971. this._joystickPointerStartPos.y = e.clientY;
  94972. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94973. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94974. this._deltaJoystickVector.x = 0;
  94975. this._deltaJoystickVector.y = 0;
  94976. this.pressed = true;
  94977. this._touches.add(e.pointerId.toString(), e);
  94978. }
  94979. else {
  94980. // You can only trigger the action buttons with a joystick declared
  94981. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94982. this._action();
  94983. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94984. }
  94985. }
  94986. };
  94987. VirtualJoystick.prototype._onPointerMove = function (e) {
  94988. // If the current pointer is the one associated to the joystick (first touch contact)
  94989. if (this._joystickPointerID == e.pointerId) {
  94990. this._joystickPointerPos.x = e.clientX;
  94991. this._joystickPointerPos.y = e.clientY;
  94992. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94993. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94994. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94995. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94996. switch (this._axisTargetedByLeftAndRight) {
  94997. case JoystickAxis.X:
  94998. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94999. break;
  95000. case JoystickAxis.Y:
  95001. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  95002. break;
  95003. case JoystickAxis.Z:
  95004. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  95005. break;
  95006. }
  95007. var directionUpDown = this.reverseUpDown ? 1 : -1;
  95008. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  95009. switch (this._axisTargetedByUpAndDown) {
  95010. case JoystickAxis.X:
  95011. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  95012. break;
  95013. case JoystickAxis.Y:
  95014. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  95015. break;
  95016. case JoystickAxis.Z:
  95017. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  95018. break;
  95019. }
  95020. }
  95021. else {
  95022. var data = this._touches.get(e.pointerId.toString());
  95023. if (data) {
  95024. data.x = e.clientX;
  95025. data.y = e.clientY;
  95026. }
  95027. }
  95028. };
  95029. VirtualJoystick.prototype._onPointerUp = function (e) {
  95030. if (this._joystickPointerID == e.pointerId) {
  95031. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  95032. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  95033. this._joystickPointerID = -1;
  95034. this.pressed = false;
  95035. }
  95036. else {
  95037. var touch = this._touches.get(e.pointerId.toString());
  95038. if (touch) {
  95039. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95040. }
  95041. }
  95042. this._deltaJoystickVector.x = 0;
  95043. this._deltaJoystickVector.y = 0;
  95044. this._touches.remove(e.pointerId.toString());
  95045. };
  95046. /**
  95047. * Change the color of the virtual joystick
  95048. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  95049. */
  95050. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  95051. this._joystickColor = newColor;
  95052. };
  95053. /**
  95054. * Defines a callback to call when the joystick is touched
  95055. * @param action defines the callback
  95056. */
  95057. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  95058. this._action = action;
  95059. };
  95060. /**
  95061. * Defines which axis you'd like to control for left & right
  95062. * @param axis defines the axis to use
  95063. */
  95064. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  95065. switch (axis) {
  95066. case JoystickAxis.X:
  95067. case JoystickAxis.Y:
  95068. case JoystickAxis.Z:
  95069. this._axisTargetedByLeftAndRight = axis;
  95070. break;
  95071. default:
  95072. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  95073. break;
  95074. }
  95075. };
  95076. /**
  95077. * Defines which axis you'd like to control for up & down
  95078. * @param axis defines the axis to use
  95079. */
  95080. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  95081. switch (axis) {
  95082. case JoystickAxis.X:
  95083. case JoystickAxis.Y:
  95084. case JoystickAxis.Z:
  95085. this._axisTargetedByUpAndDown = axis;
  95086. break;
  95087. default:
  95088. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  95089. break;
  95090. }
  95091. };
  95092. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  95093. var _this = this;
  95094. if (this.pressed) {
  95095. this._touches.forEach(function (key, touch) {
  95096. if (touch.pointerId === _this._joystickPointerID) {
  95097. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  95098. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  95099. VirtualJoystick.vjCanvasContext.beginPath();
  95100. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95101. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95102. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  95103. VirtualJoystick.vjCanvasContext.stroke();
  95104. VirtualJoystick.vjCanvasContext.closePath();
  95105. VirtualJoystick.vjCanvasContext.beginPath();
  95106. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95107. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  95108. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  95109. VirtualJoystick.vjCanvasContext.stroke();
  95110. VirtualJoystick.vjCanvasContext.closePath();
  95111. VirtualJoystick.vjCanvasContext.beginPath();
  95112. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  95113. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  95114. VirtualJoystick.vjCanvasContext.stroke();
  95115. VirtualJoystick.vjCanvasContext.closePath();
  95116. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  95117. }
  95118. else {
  95119. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  95120. VirtualJoystick.vjCanvasContext.beginPath();
  95121. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  95122. VirtualJoystick.vjCanvasContext.beginPath();
  95123. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  95124. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  95125. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  95126. VirtualJoystick.vjCanvasContext.stroke();
  95127. VirtualJoystick.vjCanvasContext.closePath();
  95128. touch.prevX = touch.x;
  95129. touch.prevY = touch.y;
  95130. }
  95131. ;
  95132. });
  95133. }
  95134. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  95135. };
  95136. /**
  95137. * Release internal HTML canvas
  95138. */
  95139. VirtualJoystick.prototype.releaseCanvas = function () {
  95140. if (VirtualJoystick.vjCanvas) {
  95141. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  95142. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  95143. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  95144. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  95145. window.removeEventListener("resize", this._onResize);
  95146. document.body.removeChild(VirtualJoystick.vjCanvas);
  95147. VirtualJoystick.vjCanvas = null;
  95148. }
  95149. };
  95150. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  95151. VirtualJoystick._globalJoystickIndex = 0;
  95152. return VirtualJoystick;
  95153. }());
  95154. BABYLON.VirtualJoystick = VirtualJoystick;
  95155. })(BABYLON || (BABYLON = {}));
  95156. //# sourceMappingURL=babylon.virtualJoystick.js.map
  95157. var BABYLON;
  95158. (function (BABYLON) {
  95159. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  95160. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  95161. });
  95162. // We're mainly based on the logic defined into the FreeCamera code
  95163. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  95164. __extends(VirtualJoysticksCamera, _super);
  95165. function VirtualJoysticksCamera(name, position, scene) {
  95166. var _this = _super.call(this, name, position, scene) || this;
  95167. _this.inputs.addVirtualJoystick();
  95168. return _this;
  95169. }
  95170. VirtualJoysticksCamera.prototype.getClassName = function () {
  95171. return "VirtualJoysticksCamera";
  95172. };
  95173. return VirtualJoysticksCamera;
  95174. }(BABYLON.FreeCamera));
  95175. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  95176. })(BABYLON || (BABYLON = {}));
  95177. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  95178. var BABYLON;
  95179. (function (BABYLON) {
  95180. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  95181. function FreeCameraVirtualJoystickInput() {
  95182. }
  95183. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  95184. return this._leftjoystick;
  95185. };
  95186. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  95187. return this._rightjoystick;
  95188. };
  95189. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  95190. if (this._leftjoystick) {
  95191. var camera = this.camera;
  95192. var speed = camera._computeLocalCameraSpeed() * 50;
  95193. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  95194. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  95195. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  95196. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  95197. if (!this._leftjoystick.pressed) {
  95198. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  95199. }
  95200. if (!this._rightjoystick.pressed) {
  95201. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  95202. }
  95203. }
  95204. };
  95205. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  95206. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  95207. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  95208. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  95209. this._leftjoystick.setJoystickSensibility(0.15);
  95210. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  95211. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  95212. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  95213. this._rightjoystick.reverseUpDown = true;
  95214. this._rightjoystick.setJoystickSensibility(0.05);
  95215. this._rightjoystick.setJoystickColor("yellow");
  95216. };
  95217. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  95218. this._leftjoystick.releaseCanvas();
  95219. this._rightjoystick.releaseCanvas();
  95220. };
  95221. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  95222. return "FreeCameraVirtualJoystickInput";
  95223. };
  95224. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  95225. return "virtualJoystick";
  95226. };
  95227. return FreeCameraVirtualJoystickInput;
  95228. }());
  95229. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  95230. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  95231. })(BABYLON || (BABYLON = {}));
  95232. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  95233. var BABYLON;
  95234. (function (BABYLON) {
  95235. var SimplificationSettings = /** @class */ (function () {
  95236. function SimplificationSettings(quality, distance, optimizeMesh) {
  95237. this.quality = quality;
  95238. this.distance = distance;
  95239. this.optimizeMesh = optimizeMesh;
  95240. }
  95241. return SimplificationSettings;
  95242. }());
  95243. BABYLON.SimplificationSettings = SimplificationSettings;
  95244. var SimplificationQueue = /** @class */ (function () {
  95245. function SimplificationQueue() {
  95246. this.running = false;
  95247. this._simplificationArray = [];
  95248. }
  95249. SimplificationQueue.prototype.addTask = function (task) {
  95250. this._simplificationArray.push(task);
  95251. };
  95252. SimplificationQueue.prototype.executeNext = function () {
  95253. var task = this._simplificationArray.pop();
  95254. if (task) {
  95255. this.running = true;
  95256. this.runSimplification(task);
  95257. }
  95258. else {
  95259. this.running = false;
  95260. }
  95261. };
  95262. SimplificationQueue.prototype.runSimplification = function (task) {
  95263. var _this = this;
  95264. if (task.parallelProcessing) {
  95265. //parallel simplifier
  95266. task.settings.forEach(function (setting) {
  95267. var simplifier = _this.getSimplifier(task);
  95268. simplifier.simplify(setting, function (newMesh) {
  95269. task.mesh.addLODLevel(setting.distance, newMesh);
  95270. newMesh.isVisible = true;
  95271. //check if it is the last
  95272. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  95273. //all done, run the success callback.
  95274. task.successCallback();
  95275. }
  95276. _this.executeNext();
  95277. });
  95278. });
  95279. }
  95280. else {
  95281. //single simplifier.
  95282. var simplifier = this.getSimplifier(task);
  95283. var runDecimation = function (setting, callback) {
  95284. simplifier.simplify(setting, function (newMesh) {
  95285. task.mesh.addLODLevel(setting.distance, newMesh);
  95286. newMesh.isVisible = true;
  95287. //run the next quality level
  95288. callback();
  95289. });
  95290. };
  95291. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  95292. runDecimation(task.settings[loop.index], function () {
  95293. loop.executeNext();
  95294. });
  95295. }, function () {
  95296. //execution ended, run the success callback.
  95297. if (task.successCallback) {
  95298. task.successCallback();
  95299. }
  95300. _this.executeNext();
  95301. });
  95302. }
  95303. };
  95304. SimplificationQueue.prototype.getSimplifier = function (task) {
  95305. switch (task.simplificationType) {
  95306. case SimplificationType.QUADRATIC:
  95307. default:
  95308. return new QuadraticErrorSimplification(task.mesh);
  95309. }
  95310. };
  95311. return SimplificationQueue;
  95312. }());
  95313. BABYLON.SimplificationQueue = SimplificationQueue;
  95314. /**
  95315. * The implemented types of simplification
  95316. * At the moment only Quadratic Error Decimation is implemented
  95317. */
  95318. var SimplificationType;
  95319. (function (SimplificationType) {
  95320. /** Quadratic error decimation */
  95321. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  95322. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  95323. var DecimationTriangle = /** @class */ (function () {
  95324. function DecimationTriangle(vertices) {
  95325. this.vertices = vertices;
  95326. this.error = new Array(4);
  95327. this.deleted = false;
  95328. this.isDirty = false;
  95329. this.deletePending = false;
  95330. this.borderFactor = 0;
  95331. }
  95332. return DecimationTriangle;
  95333. }());
  95334. BABYLON.DecimationTriangle = DecimationTriangle;
  95335. var DecimationVertex = /** @class */ (function () {
  95336. function DecimationVertex(position, id) {
  95337. this.position = position;
  95338. this.id = id;
  95339. this.isBorder = true;
  95340. this.q = new QuadraticMatrix();
  95341. this.triangleCount = 0;
  95342. this.triangleStart = 0;
  95343. this.originalOffsets = [];
  95344. }
  95345. DecimationVertex.prototype.updatePosition = function (newPosition) {
  95346. this.position.copyFrom(newPosition);
  95347. };
  95348. return DecimationVertex;
  95349. }());
  95350. BABYLON.DecimationVertex = DecimationVertex;
  95351. var QuadraticMatrix = /** @class */ (function () {
  95352. function QuadraticMatrix(data) {
  95353. this.data = new Array(10);
  95354. for (var i = 0; i < 10; ++i) {
  95355. if (data && data[i]) {
  95356. this.data[i] = data[i];
  95357. }
  95358. else {
  95359. this.data[i] = 0;
  95360. }
  95361. }
  95362. }
  95363. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  95364. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  95365. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  95366. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  95367. return det;
  95368. };
  95369. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  95370. for (var i = 0; i < 10; ++i) {
  95371. this.data[i] += matrix.data[i];
  95372. }
  95373. };
  95374. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  95375. for (var i = 0; i < 10; ++i) {
  95376. this.data[i] += data[i];
  95377. }
  95378. };
  95379. QuadraticMatrix.prototype.add = function (matrix) {
  95380. var m = new QuadraticMatrix();
  95381. for (var i = 0; i < 10; ++i) {
  95382. m.data[i] = this.data[i] + matrix.data[i];
  95383. }
  95384. return m;
  95385. };
  95386. QuadraticMatrix.FromData = function (a, b, c, d) {
  95387. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  95388. };
  95389. //returning an array to avoid garbage collection
  95390. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  95391. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  95392. };
  95393. return QuadraticMatrix;
  95394. }());
  95395. BABYLON.QuadraticMatrix = QuadraticMatrix;
  95396. var Reference = /** @class */ (function () {
  95397. function Reference(vertexId, triangleId) {
  95398. this.vertexId = vertexId;
  95399. this.triangleId = triangleId;
  95400. }
  95401. return Reference;
  95402. }());
  95403. BABYLON.Reference = Reference;
  95404. /**
  95405. * An implementation of the Quadratic Error simplification algorithm.
  95406. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  95407. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  95408. * @author RaananW
  95409. */
  95410. var QuadraticErrorSimplification = /** @class */ (function () {
  95411. function QuadraticErrorSimplification(_mesh) {
  95412. this._mesh = _mesh;
  95413. this.syncIterations = 5000;
  95414. this.aggressiveness = 7;
  95415. this.decimationIterations = 100;
  95416. this.boundingBoxEpsilon = BABYLON.Epsilon;
  95417. }
  95418. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  95419. var _this = this;
  95420. this.initDecimatedMesh();
  95421. //iterating through the submeshes array, one after the other.
  95422. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  95423. _this.initWithMesh(loop.index, function () {
  95424. _this.runDecimation(settings, loop.index, function () {
  95425. loop.executeNext();
  95426. });
  95427. }, settings.optimizeMesh);
  95428. }, function () {
  95429. setTimeout(function () {
  95430. successCallback(_this._reconstructedMesh);
  95431. }, 0);
  95432. });
  95433. };
  95434. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  95435. var _this = this;
  95436. var targetCount = ~~(this.triangles.length * settings.quality);
  95437. var deletedTriangles = 0;
  95438. var triangleCount = this.triangles.length;
  95439. var iterationFunction = function (iteration, callback) {
  95440. setTimeout(function () {
  95441. if (iteration % 5 === 0) {
  95442. _this.updateMesh(iteration === 0);
  95443. }
  95444. for (var i = 0; i < _this.triangles.length; ++i) {
  95445. _this.triangles[i].isDirty = false;
  95446. }
  95447. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  95448. var trianglesIterator = function (i) {
  95449. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  95450. var t = _this.triangles[tIdx];
  95451. if (!t)
  95452. return;
  95453. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  95454. return;
  95455. }
  95456. for (var j = 0; j < 3; ++j) {
  95457. if (t.error[j] < threshold) {
  95458. var deleted0 = [];
  95459. var deleted1 = [];
  95460. var v0 = t.vertices[j];
  95461. var v1 = t.vertices[(j + 1) % 3];
  95462. if (v0.isBorder || v1.isBorder)
  95463. continue;
  95464. var p = BABYLON.Vector3.Zero();
  95465. var n = BABYLON.Vector3.Zero();
  95466. var uv = BABYLON.Vector2.Zero();
  95467. var color = new BABYLON.Color4(0, 0, 0, 1);
  95468. _this.calculateError(v0, v1, p, n, uv, color);
  95469. var delTr = new Array();
  95470. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  95471. continue;
  95472. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  95473. continue;
  95474. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  95475. continue;
  95476. var uniqueArray = new Array();
  95477. delTr.forEach(function (deletedT) {
  95478. if (uniqueArray.indexOf(deletedT) === -1) {
  95479. deletedT.deletePending = true;
  95480. uniqueArray.push(deletedT);
  95481. }
  95482. });
  95483. if (uniqueArray.length % 2 !== 0) {
  95484. continue;
  95485. }
  95486. v0.q = v1.q.add(v0.q);
  95487. v0.updatePosition(p);
  95488. var tStart = _this.references.length;
  95489. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  95490. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  95491. var tCount = _this.references.length - tStart;
  95492. if (tCount <= v0.triangleCount) {
  95493. if (tCount) {
  95494. for (var c = 0; c < tCount; c++) {
  95495. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  95496. }
  95497. }
  95498. }
  95499. else {
  95500. v0.triangleStart = tStart;
  95501. }
  95502. v0.triangleCount = tCount;
  95503. break;
  95504. }
  95505. }
  95506. };
  95507. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  95508. }, 0);
  95509. };
  95510. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  95511. if (triangleCount - deletedTriangles <= targetCount)
  95512. loop.breakLoop();
  95513. else {
  95514. iterationFunction(loop.index, function () {
  95515. loop.executeNext();
  95516. });
  95517. }
  95518. }, function () {
  95519. setTimeout(function () {
  95520. //reconstruct this part of the mesh
  95521. _this.reconstructMesh(submeshIndex);
  95522. successCallback();
  95523. }, 0);
  95524. });
  95525. };
  95526. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  95527. var _this = this;
  95528. this.vertices = [];
  95529. this.triangles = [];
  95530. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95531. var indices = this._mesh.getIndices();
  95532. var submesh = this._mesh.subMeshes[submeshIndex];
  95533. var findInVertices = function (positionToSearch) {
  95534. if (optimizeMesh) {
  95535. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  95536. if (_this.vertices[ii].position.equals(positionToSearch)) {
  95537. return _this.vertices[ii];
  95538. }
  95539. }
  95540. }
  95541. return null;
  95542. };
  95543. var vertexReferences = [];
  95544. var vertexInit = function (i) {
  95545. if (!positionData) {
  95546. return;
  95547. }
  95548. var offset = i + submesh.verticesStart;
  95549. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  95550. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  95551. vertex.originalOffsets.push(offset);
  95552. if (vertex.id === _this.vertices.length) {
  95553. _this.vertices.push(vertex);
  95554. }
  95555. vertexReferences.push(vertex.id);
  95556. };
  95557. //var totalVertices = mesh.getTotalVertices();
  95558. var totalVertices = submesh.verticesCount;
  95559. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  95560. var indicesInit = function (i) {
  95561. if (!indices) {
  95562. return;
  95563. }
  95564. var offset = (submesh.indexStart / 3) + i;
  95565. var pos = (offset * 3);
  95566. var i0 = indices[pos + 0];
  95567. var i1 = indices[pos + 1];
  95568. var i2 = indices[pos + 2];
  95569. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  95570. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  95571. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  95572. var triangle = new DecimationTriangle([v0, v1, v2]);
  95573. triangle.originalOffset = pos;
  95574. _this.triangles.push(triangle);
  95575. };
  95576. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  95577. _this.init(callback);
  95578. });
  95579. });
  95580. };
  95581. QuadraticErrorSimplification.prototype.init = function (callback) {
  95582. var _this = this;
  95583. var triangleInit1 = function (i) {
  95584. var t = _this.triangles[i];
  95585. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  95586. for (var j = 0; j < 3; j++) {
  95587. 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))));
  95588. }
  95589. };
  95590. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  95591. var triangleInit2 = function (i) {
  95592. var t = _this.triangles[i];
  95593. for (var j = 0; j < 3; ++j) {
  95594. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  95595. }
  95596. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95597. };
  95598. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  95599. callback();
  95600. });
  95601. });
  95602. };
  95603. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  95604. var newTriangles = [];
  95605. var i;
  95606. for (i = 0; i < this.vertices.length; ++i) {
  95607. this.vertices[i].triangleCount = 0;
  95608. }
  95609. var t;
  95610. var j;
  95611. for (i = 0; i < this.triangles.length; ++i) {
  95612. if (!this.triangles[i].deleted) {
  95613. t = this.triangles[i];
  95614. for (j = 0; j < 3; ++j) {
  95615. t.vertices[j].triangleCount = 1;
  95616. }
  95617. newTriangles.push(t);
  95618. }
  95619. }
  95620. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  95621. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  95622. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  95623. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  95624. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  95625. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  95626. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  95627. var vertexCount = 0;
  95628. for (i = 0; i < this.vertices.length; ++i) {
  95629. var vertex = this.vertices[i];
  95630. vertex.id = vertexCount;
  95631. if (vertex.triangleCount) {
  95632. vertex.originalOffsets.forEach(function (originalOffset) {
  95633. if (!normalData) {
  95634. return;
  95635. }
  95636. newPositionData.push(vertex.position.x);
  95637. newPositionData.push(vertex.position.y);
  95638. newPositionData.push(vertex.position.z);
  95639. newNormalData.push(normalData[originalOffset * 3]);
  95640. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  95641. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  95642. if (uvs && uvs.length) {
  95643. newUVsData.push(uvs[(originalOffset * 2)]);
  95644. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  95645. }
  95646. else if (colorsData && colorsData.length) {
  95647. newColorsData.push(colorsData[(originalOffset * 4)]);
  95648. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  95649. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  95650. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  95651. }
  95652. ++vertexCount;
  95653. });
  95654. }
  95655. }
  95656. var startingIndex = this._reconstructedMesh.getTotalIndices();
  95657. var startingVertex = this._reconstructedMesh.getTotalVertices();
  95658. var submeshesArray = this._reconstructedMesh.subMeshes;
  95659. this._reconstructedMesh.subMeshes = [];
  95660. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  95661. var originalIndices = this._mesh.getIndices();
  95662. for (i = 0; i < newTriangles.length; ++i) {
  95663. t = newTriangles[i]; //now get the new referencing point for each vertex
  95664. [0, 1, 2].forEach(function (idx) {
  95665. var id = originalIndices[t.originalOffset + idx];
  95666. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  95667. if (offset < 0)
  95668. offset = 0;
  95669. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  95670. });
  95671. }
  95672. //overwriting the old vertex buffers and indices.
  95673. this._reconstructedMesh.setIndices(newIndicesArray);
  95674. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  95675. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  95676. if (newUVsData.length > 0)
  95677. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  95678. if (newColorsData.length > 0)
  95679. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  95680. //create submesh
  95681. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  95682. if (submeshIndex > 0) {
  95683. this._reconstructedMesh.subMeshes = [];
  95684. submeshesArray.forEach(function (submesh) {
  95685. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  95686. });
  95687. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  95688. }
  95689. };
  95690. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  95691. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  95692. this._reconstructedMesh.material = this._mesh.material;
  95693. this._reconstructedMesh.parent = this._mesh.parent;
  95694. this._reconstructedMesh.isVisible = false;
  95695. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  95696. };
  95697. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  95698. for (var i = 0; i < vertex1.triangleCount; ++i) {
  95699. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  95700. if (t.deleted)
  95701. continue;
  95702. var s = this.references[vertex1.triangleStart + i].vertexId;
  95703. var v1 = t.vertices[(s + 1) % 3];
  95704. var v2 = t.vertices[(s + 2) % 3];
  95705. if ((v1 === vertex2 || v2 === vertex2)) {
  95706. deletedArray[i] = true;
  95707. delTr.push(t);
  95708. continue;
  95709. }
  95710. var d1 = v1.position.subtract(point);
  95711. d1 = d1.normalize();
  95712. var d2 = v2.position.subtract(point);
  95713. d2 = d2.normalize();
  95714. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  95715. return true;
  95716. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  95717. deletedArray[i] = false;
  95718. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  95719. return true;
  95720. }
  95721. return false;
  95722. };
  95723. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  95724. var newDeleted = deletedTriangles;
  95725. for (var i = 0; i < vertex.triangleCount; ++i) {
  95726. var ref = this.references[vertex.triangleStart + i];
  95727. var t = this.triangles[ref.triangleId];
  95728. if (t.deleted)
  95729. continue;
  95730. if (deletedArray[i] && t.deletePending) {
  95731. t.deleted = true;
  95732. newDeleted++;
  95733. continue;
  95734. }
  95735. t.vertices[ref.vertexId] = origVertex;
  95736. t.isDirty = true;
  95737. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  95738. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  95739. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  95740. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  95741. this.references.push(ref);
  95742. }
  95743. return newDeleted;
  95744. };
  95745. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  95746. for (var i = 0; i < this.vertices.length; ++i) {
  95747. var vCount = [];
  95748. var vId = [];
  95749. var v = this.vertices[i];
  95750. var j;
  95751. for (j = 0; j < v.triangleCount; ++j) {
  95752. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  95753. for (var ii = 0; ii < 3; ii++) {
  95754. var ofs = 0;
  95755. var vv = triangle.vertices[ii];
  95756. while (ofs < vCount.length) {
  95757. if (vId[ofs] === vv.id)
  95758. break;
  95759. ++ofs;
  95760. }
  95761. if (ofs === vCount.length) {
  95762. vCount.push(1);
  95763. vId.push(vv.id);
  95764. }
  95765. else {
  95766. vCount[ofs]++;
  95767. }
  95768. }
  95769. }
  95770. for (j = 0; j < vCount.length; ++j) {
  95771. if (vCount[j] === 1) {
  95772. this.vertices[vId[j]].isBorder = true;
  95773. }
  95774. else {
  95775. this.vertices[vId[j]].isBorder = false;
  95776. }
  95777. }
  95778. }
  95779. };
  95780. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  95781. if (identifyBorders === void 0) { identifyBorders = false; }
  95782. var i;
  95783. if (!identifyBorders) {
  95784. var newTrianglesVector = [];
  95785. for (i = 0; i < this.triangles.length; ++i) {
  95786. if (!this.triangles[i].deleted) {
  95787. newTrianglesVector.push(this.triangles[i]);
  95788. }
  95789. }
  95790. this.triangles = newTrianglesVector;
  95791. }
  95792. for (i = 0; i < this.vertices.length; ++i) {
  95793. this.vertices[i].triangleCount = 0;
  95794. this.vertices[i].triangleStart = 0;
  95795. }
  95796. var t;
  95797. var j;
  95798. var v;
  95799. for (i = 0; i < this.triangles.length; ++i) {
  95800. t = this.triangles[i];
  95801. for (j = 0; j < 3; ++j) {
  95802. v = t.vertices[j];
  95803. v.triangleCount++;
  95804. }
  95805. }
  95806. var tStart = 0;
  95807. for (i = 0; i < this.vertices.length; ++i) {
  95808. this.vertices[i].triangleStart = tStart;
  95809. tStart += this.vertices[i].triangleCount;
  95810. this.vertices[i].triangleCount = 0;
  95811. }
  95812. var newReferences = new Array(this.triangles.length * 3);
  95813. for (i = 0; i < this.triangles.length; ++i) {
  95814. t = this.triangles[i];
  95815. for (j = 0; j < 3; ++j) {
  95816. v = t.vertices[j];
  95817. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  95818. v.triangleCount++;
  95819. }
  95820. }
  95821. this.references = newReferences;
  95822. if (identifyBorders) {
  95823. this.identifyBorder();
  95824. }
  95825. };
  95826. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  95827. var x = point.x;
  95828. var y = point.y;
  95829. var z = point.z;
  95830. 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
  95831. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  95832. };
  95833. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  95834. var q = vertex1.q.add(vertex2.q);
  95835. var border = vertex1.isBorder && vertex2.isBorder;
  95836. var error = 0;
  95837. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  95838. if (qDet !== 0 && !border) {
  95839. if (!pointResult) {
  95840. pointResult = BABYLON.Vector3.Zero();
  95841. }
  95842. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  95843. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  95844. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  95845. error = this.vertexError(q, pointResult);
  95846. }
  95847. else {
  95848. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  95849. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  95850. var error1 = this.vertexError(q, vertex1.position);
  95851. var error2 = this.vertexError(q, vertex2.position);
  95852. var error3 = this.vertexError(q, p3);
  95853. error = Math.min(error1, error2, error3);
  95854. if (error === error1) {
  95855. if (pointResult) {
  95856. pointResult.copyFrom(vertex1.position);
  95857. }
  95858. }
  95859. else if (error === error2) {
  95860. if (pointResult) {
  95861. pointResult.copyFrom(vertex2.position);
  95862. }
  95863. }
  95864. else {
  95865. if (pointResult) {
  95866. pointResult.copyFrom(p3);
  95867. }
  95868. }
  95869. }
  95870. return error;
  95871. };
  95872. return QuadraticErrorSimplification;
  95873. }());
  95874. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95875. })(BABYLON || (BABYLON = {}));
  95876. //# sourceMappingURL=babylon.meshSimplification.js.map
  95877. var BABYLON;
  95878. (function (BABYLON) {
  95879. var MeshLODLevel = /** @class */ (function () {
  95880. function MeshLODLevel(distance, mesh) {
  95881. this.distance = distance;
  95882. this.mesh = mesh;
  95883. }
  95884. return MeshLODLevel;
  95885. }());
  95886. BABYLON.MeshLODLevel = MeshLODLevel;
  95887. })(BABYLON || (BABYLON = {}));
  95888. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95889. var BABYLON;
  95890. (function (BABYLON) {
  95891. /**
  95892. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95893. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95894. */
  95895. var SceneOptimization = /** @class */ (function () {
  95896. /**
  95897. * Creates the SceneOptimization object
  95898. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95899. * @param desc defines the description associated with the optimization
  95900. */
  95901. function SceneOptimization(
  95902. /**
  95903. * Defines the priority of this optimization (0 by default which means first in the list)
  95904. */
  95905. priority) {
  95906. if (priority === void 0) { priority = 0; }
  95907. this.priority = priority;
  95908. }
  95909. /**
  95910. * Gets a string describing the action executed by the current optimization
  95911. * @returns description string
  95912. */
  95913. SceneOptimization.prototype.getDescription = function () {
  95914. return "";
  95915. };
  95916. /**
  95917. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95918. * @param scene defines the current scene where to apply this optimization
  95919. * @param optimizer defines the current optimizer
  95920. * @returns true if everything that can be done was applied
  95921. */
  95922. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95923. return true;
  95924. };
  95925. ;
  95926. return SceneOptimization;
  95927. }());
  95928. BABYLON.SceneOptimization = SceneOptimization;
  95929. /**
  95930. * Defines an optimization used to reduce the size of render target textures
  95931. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95932. */
  95933. var TextureOptimization = /** @class */ (function (_super) {
  95934. __extends(TextureOptimization, _super);
  95935. /**
  95936. * Creates the TextureOptimization object
  95937. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95938. * @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
  95939. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95940. */
  95941. function TextureOptimization(
  95942. /**
  95943. * Defines the priority of this optimization (0 by default which means first in the list)
  95944. */
  95945. priority,
  95946. /**
  95947. * 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
  95948. */
  95949. maximumSize,
  95950. /**
  95951. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95952. */
  95953. step) {
  95954. if (priority === void 0) { priority = 0; }
  95955. if (maximumSize === void 0) { maximumSize = 1024; }
  95956. if (step === void 0) { step = 0.5; }
  95957. var _this = _super.call(this, priority) || this;
  95958. _this.priority = priority;
  95959. _this.maximumSize = maximumSize;
  95960. _this.step = step;
  95961. return _this;
  95962. }
  95963. /**
  95964. * Gets a string describing the action executed by the current optimization
  95965. * @returns description string
  95966. */
  95967. TextureOptimization.prototype.getDescription = function () {
  95968. return "Reducing render target texture size to " + this.maximumSize;
  95969. };
  95970. /**
  95971. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95972. * @param scene defines the current scene where to apply this optimization
  95973. * @param optimizer defines the current optimizer
  95974. * @returns true if everything that can be done was applied
  95975. */
  95976. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95977. var allDone = true;
  95978. for (var index = 0; index < scene.textures.length; index++) {
  95979. var texture = scene.textures[index];
  95980. if (!texture.canRescale || texture.getContext) {
  95981. continue;
  95982. }
  95983. var currentSize = texture.getSize();
  95984. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95985. if (maxDimension > this.maximumSize) {
  95986. texture.scale(this.step);
  95987. allDone = false;
  95988. }
  95989. }
  95990. return allDone;
  95991. };
  95992. return TextureOptimization;
  95993. }(SceneOptimization));
  95994. BABYLON.TextureOptimization = TextureOptimization;
  95995. /**
  95996. * Defines an optimization used to increase or decrease the rendering resolution
  95997. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95998. */
  95999. var HardwareScalingOptimization = /** @class */ (function (_super) {
  96000. __extends(HardwareScalingOptimization, _super);
  96001. /**
  96002. * Creates the HardwareScalingOptimization object
  96003. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96004. * @param maximumScale defines the maximum scale to use (2 by default)
  96005. * @param step defines the step to use between two passes (0.5 by default)
  96006. */
  96007. function HardwareScalingOptimization(
  96008. /**
  96009. * Defines the priority of this optimization (0 by default which means first in the list)
  96010. */
  96011. priority,
  96012. /**
  96013. * Defines the maximum scale to use (2 by default)
  96014. */
  96015. maximumScale,
  96016. /**
  96017. * Defines the step to use between two passes (0.5 by default)
  96018. */
  96019. step) {
  96020. if (priority === void 0) { priority = 0; }
  96021. if (maximumScale === void 0) { maximumScale = 2; }
  96022. if (step === void 0) { step = 0.25; }
  96023. var _this = _super.call(this, priority) || this;
  96024. _this.priority = priority;
  96025. _this.maximumScale = maximumScale;
  96026. _this.step = step;
  96027. _this._currentScale = -1;
  96028. _this._directionOffset = 1;
  96029. return _this;
  96030. }
  96031. /**
  96032. * Gets a string describing the action executed by the current optimization
  96033. * @return description string
  96034. */
  96035. HardwareScalingOptimization.prototype.getDescription = function () {
  96036. return "Setting hardware scaling level to " + this._currentScale;
  96037. };
  96038. /**
  96039. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96040. * @param scene defines the current scene where to apply this optimization
  96041. * @param optimizer defines the current optimizer
  96042. * @returns true if everything that can be done was applied
  96043. */
  96044. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  96045. if (this._currentScale === -1) {
  96046. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  96047. if (this._currentScale > this.maximumScale) {
  96048. this._directionOffset = -1;
  96049. }
  96050. }
  96051. this._currentScale += this._directionOffset * this.step;
  96052. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  96053. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  96054. };
  96055. ;
  96056. return HardwareScalingOptimization;
  96057. }(SceneOptimization));
  96058. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  96059. /**
  96060. * Defines an optimization used to remove shadows
  96061. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96062. */
  96063. var ShadowsOptimization = /** @class */ (function (_super) {
  96064. __extends(ShadowsOptimization, _super);
  96065. function ShadowsOptimization() {
  96066. return _super !== null && _super.apply(this, arguments) || this;
  96067. }
  96068. /**
  96069. * Gets a string describing the action executed by the current optimization
  96070. * @return description string
  96071. */
  96072. ShadowsOptimization.prototype.getDescription = function () {
  96073. return "Turning shadows on/off";
  96074. };
  96075. /**
  96076. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96077. * @param scene defines the current scene where to apply this optimization
  96078. * @param optimizer defines the current optimizer
  96079. * @returns true if everything that can be done was applied
  96080. */
  96081. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  96082. scene.shadowsEnabled = optimizer.isInImprovementMode;
  96083. return true;
  96084. };
  96085. ;
  96086. return ShadowsOptimization;
  96087. }(SceneOptimization));
  96088. BABYLON.ShadowsOptimization = ShadowsOptimization;
  96089. /**
  96090. * Defines an optimization used to turn post-processes off
  96091. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96092. */
  96093. var PostProcessesOptimization = /** @class */ (function (_super) {
  96094. __extends(PostProcessesOptimization, _super);
  96095. function PostProcessesOptimization() {
  96096. return _super !== null && _super.apply(this, arguments) || this;
  96097. }
  96098. /**
  96099. * Gets a string describing the action executed by the current optimization
  96100. * @return description string
  96101. */
  96102. PostProcessesOptimization.prototype.getDescription = function () {
  96103. return "Turning post-processes on/off";
  96104. };
  96105. /**
  96106. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96107. * @param scene defines the current scene where to apply this optimization
  96108. * @param optimizer defines the current optimizer
  96109. * @returns true if everything that can be done was applied
  96110. */
  96111. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  96112. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  96113. return true;
  96114. };
  96115. ;
  96116. return PostProcessesOptimization;
  96117. }(SceneOptimization));
  96118. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  96119. /**
  96120. * Defines an optimization used to turn lens flares off
  96121. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96122. */
  96123. var LensFlaresOptimization = /** @class */ (function (_super) {
  96124. __extends(LensFlaresOptimization, _super);
  96125. function LensFlaresOptimization() {
  96126. return _super !== null && _super.apply(this, arguments) || this;
  96127. }
  96128. /**
  96129. * Gets a string describing the action executed by the current optimization
  96130. * @return description string
  96131. */
  96132. LensFlaresOptimization.prototype.getDescription = function () {
  96133. return "Turning lens flares on/off";
  96134. };
  96135. /**
  96136. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96137. * @param scene defines the current scene where to apply this optimization
  96138. * @param optimizer defines the current optimizer
  96139. * @returns true if everything that can be done was applied
  96140. */
  96141. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  96142. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  96143. return true;
  96144. };
  96145. ;
  96146. return LensFlaresOptimization;
  96147. }(SceneOptimization));
  96148. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  96149. /**
  96150. * Defines an optimization based on user defined callback.
  96151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96152. */
  96153. var CustomOptimization = /** @class */ (function (_super) {
  96154. __extends(CustomOptimization, _super);
  96155. function CustomOptimization() {
  96156. return _super !== null && _super.apply(this, arguments) || this;
  96157. }
  96158. /**
  96159. * Gets a string describing the action executed by the current optimization
  96160. * @returns description string
  96161. */
  96162. CustomOptimization.prototype.getDescription = function () {
  96163. if (this.onGetDescription) {
  96164. return this.onGetDescription();
  96165. }
  96166. return "Running user defined callback";
  96167. };
  96168. /**
  96169. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96170. * @param scene defines the current scene where to apply this optimization
  96171. * @param optimizer defines the current optimizer
  96172. * @returns true if everything that can be done was applied
  96173. */
  96174. CustomOptimization.prototype.apply = function (scene, optimizer) {
  96175. if (this.onApply) {
  96176. return this.onApply(scene, optimizer);
  96177. }
  96178. return true;
  96179. };
  96180. ;
  96181. return CustomOptimization;
  96182. }(SceneOptimization));
  96183. BABYLON.CustomOptimization = CustomOptimization;
  96184. /**
  96185. * Defines an optimization used to turn particles off
  96186. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96187. */
  96188. var ParticlesOptimization = /** @class */ (function (_super) {
  96189. __extends(ParticlesOptimization, _super);
  96190. function ParticlesOptimization() {
  96191. return _super !== null && _super.apply(this, arguments) || this;
  96192. }
  96193. /**
  96194. * Gets a string describing the action executed by the current optimization
  96195. * @return description string
  96196. */
  96197. ParticlesOptimization.prototype.getDescription = function () {
  96198. return "Turning particles on/off";
  96199. };
  96200. /**
  96201. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96202. * @param scene defines the current scene where to apply this optimization
  96203. * @param optimizer defines the current optimizer
  96204. * @returns true if everything that can be done was applied
  96205. */
  96206. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  96207. scene.particlesEnabled = optimizer.isInImprovementMode;
  96208. return true;
  96209. };
  96210. ;
  96211. return ParticlesOptimization;
  96212. }(SceneOptimization));
  96213. BABYLON.ParticlesOptimization = ParticlesOptimization;
  96214. /**
  96215. * Defines an optimization used to turn render targets off
  96216. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96217. */
  96218. var RenderTargetsOptimization = /** @class */ (function (_super) {
  96219. __extends(RenderTargetsOptimization, _super);
  96220. function RenderTargetsOptimization() {
  96221. return _super !== null && _super.apply(this, arguments) || this;
  96222. }
  96223. /**
  96224. * Gets a string describing the action executed by the current optimization
  96225. * @return description string
  96226. */
  96227. RenderTargetsOptimization.prototype.getDescription = function () {
  96228. return "Turning render targets off";
  96229. };
  96230. /**
  96231. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96232. * @param scene defines the current scene where to apply this optimization
  96233. * @param optimizer defines the current optimizer
  96234. * @returns true if everything that can be done was applied
  96235. */
  96236. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  96237. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  96238. return true;
  96239. };
  96240. ;
  96241. return RenderTargetsOptimization;
  96242. }(SceneOptimization));
  96243. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  96244. /**
  96245. * Defines an optimization used to merge meshes with compatible materials
  96246. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96247. */
  96248. var MergeMeshesOptimization = /** @class */ (function (_super) {
  96249. __extends(MergeMeshesOptimization, _super);
  96250. function MergeMeshesOptimization() {
  96251. var _this = _super !== null && _super.apply(this, arguments) || this;
  96252. _this._canBeMerged = function (abstractMesh) {
  96253. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  96254. return false;
  96255. }
  96256. var mesh = abstractMesh;
  96257. if (mesh.isDisposed()) {
  96258. return false;
  96259. }
  96260. if (!mesh.isVisible || !mesh.isEnabled()) {
  96261. return false;
  96262. }
  96263. if (mesh.instances.length > 0) {
  96264. return false;
  96265. }
  96266. if (mesh.skeleton || mesh.hasLODLevels) {
  96267. return false;
  96268. }
  96269. return true;
  96270. };
  96271. return _this;
  96272. }
  96273. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  96274. /**
  96275. * Gets or sets a boolean which defines if optimization octree has to be updated
  96276. */
  96277. get: function () {
  96278. return MergeMeshesOptimization._UpdateSelectionTree;
  96279. },
  96280. /**
  96281. * Gets or sets a boolean which defines if optimization octree has to be updated
  96282. */
  96283. set: function (value) {
  96284. MergeMeshesOptimization._UpdateSelectionTree = value;
  96285. },
  96286. enumerable: true,
  96287. configurable: true
  96288. });
  96289. /**
  96290. * Gets a string describing the action executed by the current optimization
  96291. * @return description string
  96292. */
  96293. MergeMeshesOptimization.prototype.getDescription = function () {
  96294. return "Merging similar meshes together";
  96295. };
  96296. /**
  96297. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  96298. * @param scene defines the current scene where to apply this optimization
  96299. * @param optimizer defines the current optimizer
  96300. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  96301. * @returns true if everything that can be done was applied
  96302. */
  96303. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  96304. var globalPool = scene.meshes.slice(0);
  96305. var globalLength = globalPool.length;
  96306. for (var index = 0; index < globalLength; index++) {
  96307. var currentPool = new Array();
  96308. var current = globalPool[index];
  96309. // Checks
  96310. if (!this._canBeMerged(current)) {
  96311. continue;
  96312. }
  96313. currentPool.push(current);
  96314. // Find compatible meshes
  96315. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  96316. var otherMesh = globalPool[subIndex];
  96317. if (!this._canBeMerged(otherMesh)) {
  96318. continue;
  96319. }
  96320. if (otherMesh.material !== current.material) {
  96321. continue;
  96322. }
  96323. if (otherMesh.checkCollisions !== current.checkCollisions) {
  96324. continue;
  96325. }
  96326. currentPool.push(otherMesh);
  96327. globalLength--;
  96328. globalPool.splice(subIndex, 1);
  96329. subIndex--;
  96330. }
  96331. if (currentPool.length < 2) {
  96332. continue;
  96333. }
  96334. // Merge meshes
  96335. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  96336. }
  96337. if (updateSelectionTree != undefined) {
  96338. if (updateSelectionTree) {
  96339. scene.createOrUpdateSelectionOctree();
  96340. }
  96341. }
  96342. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  96343. scene.createOrUpdateSelectionOctree();
  96344. }
  96345. return true;
  96346. };
  96347. ;
  96348. MergeMeshesOptimization._UpdateSelectionTree = false;
  96349. return MergeMeshesOptimization;
  96350. }(SceneOptimization));
  96351. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  96352. /**
  96353. * Defines a list of options used by SceneOptimizer
  96354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96355. */
  96356. var SceneOptimizerOptions = /** @class */ (function () {
  96357. /**
  96358. * Creates a new list of options used by SceneOptimizer
  96359. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  96360. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  96361. */
  96362. function SceneOptimizerOptions(
  96363. /**
  96364. * Defines the target frame rate to reach (60 by default)
  96365. */
  96366. targetFrameRate,
  96367. /**
  96368. * Defines the interval between two checkes (2000ms by default)
  96369. */
  96370. trackerDuration) {
  96371. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  96372. if (trackerDuration === void 0) { trackerDuration = 2000; }
  96373. this.targetFrameRate = targetFrameRate;
  96374. this.trackerDuration = trackerDuration;
  96375. /**
  96376. * Gets the list of optimizations to apply
  96377. */
  96378. this.optimizations = new Array();
  96379. }
  96380. /**
  96381. * Add a new optimization
  96382. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  96383. * @returns the current SceneOptimizerOptions
  96384. */
  96385. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  96386. this.optimizations.push(optimization);
  96387. return this;
  96388. };
  96389. /**
  96390. * Add a new custom optimization
  96391. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  96392. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  96393. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  96394. * @returns the current SceneOptimizerOptions
  96395. */
  96396. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  96397. if (priority === void 0) { priority = 0; }
  96398. var optimization = new CustomOptimization(priority);
  96399. optimization.onApply = onApply;
  96400. optimization.onGetDescription = onGetDescription;
  96401. this.optimizations.push(optimization);
  96402. return this;
  96403. };
  96404. /**
  96405. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  96406. * @param targetFrameRate defines the target frame rate (60 by default)
  96407. * @returns a SceneOptimizerOptions object
  96408. */
  96409. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  96410. var result = new SceneOptimizerOptions(targetFrameRate);
  96411. var priority = 0;
  96412. result.addOptimization(new MergeMeshesOptimization(priority));
  96413. result.addOptimization(new ShadowsOptimization(priority));
  96414. result.addOptimization(new LensFlaresOptimization(priority));
  96415. // Next priority
  96416. priority++;
  96417. result.addOptimization(new PostProcessesOptimization(priority));
  96418. result.addOptimization(new ParticlesOptimization(priority));
  96419. // Next priority
  96420. priority++;
  96421. result.addOptimization(new TextureOptimization(priority, 1024));
  96422. return result;
  96423. };
  96424. /**
  96425. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  96426. * @param targetFrameRate defines the target frame rate (60 by default)
  96427. * @returns a SceneOptimizerOptions object
  96428. */
  96429. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  96430. var result = new SceneOptimizerOptions(targetFrameRate);
  96431. var priority = 0;
  96432. result.addOptimization(new MergeMeshesOptimization(priority));
  96433. result.addOptimization(new ShadowsOptimization(priority));
  96434. result.addOptimization(new LensFlaresOptimization(priority));
  96435. // Next priority
  96436. priority++;
  96437. result.addOptimization(new PostProcessesOptimization(priority));
  96438. result.addOptimization(new ParticlesOptimization(priority));
  96439. // Next priority
  96440. priority++;
  96441. result.addOptimization(new TextureOptimization(priority, 512));
  96442. // Next priority
  96443. priority++;
  96444. result.addOptimization(new RenderTargetsOptimization(priority));
  96445. // Next priority
  96446. priority++;
  96447. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  96448. return result;
  96449. };
  96450. /**
  96451. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  96452. * @param targetFrameRate defines the target frame rate (60 by default)
  96453. * @returns a SceneOptimizerOptions object
  96454. */
  96455. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  96456. var result = new SceneOptimizerOptions(targetFrameRate);
  96457. var priority = 0;
  96458. result.addOptimization(new MergeMeshesOptimization(priority));
  96459. result.addOptimization(new ShadowsOptimization(priority));
  96460. result.addOptimization(new LensFlaresOptimization(priority));
  96461. // Next priority
  96462. priority++;
  96463. result.addOptimization(new PostProcessesOptimization(priority));
  96464. result.addOptimization(new ParticlesOptimization(priority));
  96465. // Next priority
  96466. priority++;
  96467. result.addOptimization(new TextureOptimization(priority, 256));
  96468. // Next priority
  96469. priority++;
  96470. result.addOptimization(new RenderTargetsOptimization(priority));
  96471. // Next priority
  96472. priority++;
  96473. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  96474. return result;
  96475. };
  96476. return SceneOptimizerOptions;
  96477. }());
  96478. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  96479. /**
  96480. * Class used to run optimizations in order to reach a target frame rate
  96481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  96482. */
  96483. var SceneOptimizer = /** @class */ (function () {
  96484. /**
  96485. * Creates a new SceneOptimizer
  96486. * @param scene defines the scene to work on
  96487. * @param options defines the options to use with the SceneOptimizer
  96488. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  96489. * @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)
  96490. */
  96491. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  96492. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  96493. if (improvementMode === void 0) { improvementMode = false; }
  96494. var _this = this;
  96495. this._isRunning = false;
  96496. this._currentPriorityLevel = 0;
  96497. this._targetFrameRate = 60;
  96498. this._trackerDuration = 2000;
  96499. this._currentFrameRate = 0;
  96500. this._improvementMode = false;
  96501. /**
  96502. * Defines an observable called when the optimizer reaches the target frame rate
  96503. */
  96504. this.onSuccessObservable = new BABYLON.Observable();
  96505. /**
  96506. * Defines an observable called when the optimizer enables an optimization
  96507. */
  96508. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  96509. /**
  96510. * Defines an observable called when the optimizer is not able to reach the target frame rate
  96511. */
  96512. this.onFailureObservable = new BABYLON.Observable();
  96513. if (!options) {
  96514. this._options = new SceneOptimizerOptions();
  96515. }
  96516. else {
  96517. this._options = options;
  96518. }
  96519. if (this._options.targetFrameRate) {
  96520. this._targetFrameRate = this._options.targetFrameRate;
  96521. }
  96522. if (this._options.trackerDuration) {
  96523. this._trackerDuration = this._options.trackerDuration;
  96524. }
  96525. if (autoGeneratePriorities) {
  96526. var priority = 0;
  96527. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  96528. var optim = _a[_i];
  96529. optim.priority = priority++;
  96530. }
  96531. }
  96532. this._improvementMode = improvementMode;
  96533. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96534. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  96535. _this._sceneDisposeObserver = null;
  96536. _this.dispose();
  96537. });
  96538. }
  96539. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  96540. /**
  96541. * Gets a boolean indicating if the optimizer is in improvement mode
  96542. */
  96543. get: function () {
  96544. return this._improvementMode;
  96545. },
  96546. enumerable: true,
  96547. configurable: true
  96548. });
  96549. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  96550. /**
  96551. * Gets the current priority level (0 at start)
  96552. */
  96553. get: function () {
  96554. return this._currentPriorityLevel;
  96555. },
  96556. enumerable: true,
  96557. configurable: true
  96558. });
  96559. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  96560. /**
  96561. * Gets the current frame rate checked by the SceneOptimizer
  96562. */
  96563. get: function () {
  96564. return this._currentFrameRate;
  96565. },
  96566. enumerable: true,
  96567. configurable: true
  96568. });
  96569. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  96570. /**
  96571. * Gets or sets the current target frame rate (60 by default)
  96572. */
  96573. get: function () {
  96574. return this._targetFrameRate;
  96575. },
  96576. /**
  96577. * Gets or sets the current target frame rate (60 by default)
  96578. */
  96579. set: function (value) {
  96580. this._targetFrameRate = value;
  96581. },
  96582. enumerable: true,
  96583. configurable: true
  96584. });
  96585. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  96586. /**
  96587. * Gets or sets the current interval between two checks (every 2000ms by default)
  96588. */
  96589. get: function () {
  96590. return this._trackerDuration;
  96591. },
  96592. /**
  96593. * Gets or sets the current interval between two checks (every 2000ms by default)
  96594. */
  96595. set: function (value) {
  96596. this._trackerDuration = value;
  96597. },
  96598. enumerable: true,
  96599. configurable: true
  96600. });
  96601. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  96602. /**
  96603. * Gets the list of active optimizations
  96604. */
  96605. get: function () {
  96606. return this._options.optimizations;
  96607. },
  96608. enumerable: true,
  96609. configurable: true
  96610. });
  96611. /**
  96612. * Stops the current optimizer
  96613. */
  96614. SceneOptimizer.prototype.stop = function () {
  96615. this._isRunning = false;
  96616. };
  96617. /**
  96618. * Reset the optimizer to initial step (current priority level = 0)
  96619. */
  96620. SceneOptimizer.prototype.reset = function () {
  96621. this._currentPriorityLevel = 0;
  96622. };
  96623. /**
  96624. * Start the optimizer. By default it will try to reach a specific framerate
  96625. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  96626. */
  96627. SceneOptimizer.prototype.start = function () {
  96628. var _this = this;
  96629. if (this._isRunning) {
  96630. return;
  96631. }
  96632. this._isRunning = true;
  96633. // Let's wait for the scene to be ready before running our check
  96634. this._scene.executeWhenReady(function () {
  96635. setTimeout(function () {
  96636. _this._checkCurrentState();
  96637. }, _this._trackerDuration);
  96638. });
  96639. };
  96640. SceneOptimizer.prototype._checkCurrentState = function () {
  96641. var _this = this;
  96642. if (!this._isRunning) {
  96643. return;
  96644. }
  96645. var scene = this._scene;
  96646. var options = this._options;
  96647. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  96648. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  96649. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  96650. this._isRunning = false;
  96651. this.onSuccessObservable.notifyObservers(this);
  96652. return;
  96653. }
  96654. // Apply current level of optimizations
  96655. var allDone = true;
  96656. var noOptimizationApplied = true;
  96657. for (var index = 0; index < options.optimizations.length; index++) {
  96658. var optimization = options.optimizations[index];
  96659. if (optimization.priority === this._currentPriorityLevel) {
  96660. noOptimizationApplied = false;
  96661. allDone = allDone && optimization.apply(scene, this);
  96662. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  96663. }
  96664. }
  96665. // If no optimization was applied, this is a failure :(
  96666. if (noOptimizationApplied) {
  96667. this._isRunning = false;
  96668. this.onFailureObservable.notifyObservers(this);
  96669. return;
  96670. }
  96671. // If all optimizations were done, move to next level
  96672. if (allDone) {
  96673. this._currentPriorityLevel++;
  96674. }
  96675. // Let's the system running for a specific amount of time before checking FPS
  96676. scene.executeWhenReady(function () {
  96677. setTimeout(function () {
  96678. _this._checkCurrentState();
  96679. }, _this._trackerDuration);
  96680. });
  96681. };
  96682. /**
  96683. * Release all resources
  96684. */
  96685. SceneOptimizer.prototype.dispose = function () {
  96686. this.stop();
  96687. this.onSuccessObservable.clear();
  96688. this.onFailureObservable.clear();
  96689. this.onNewOptimizationAppliedObservable.clear();
  96690. if (this._sceneDisposeObserver) {
  96691. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  96692. }
  96693. };
  96694. /**
  96695. * Helper function to create a SceneOptimizer with one single line of code
  96696. * @param scene defines the scene to work on
  96697. * @param options defines the options to use with the SceneOptimizer
  96698. * @param onSuccess defines a callback to call on success
  96699. * @param onFailure defines a callback to call on failure
  96700. * @returns the new SceneOptimizer object
  96701. */
  96702. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  96703. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  96704. if (onSuccess) {
  96705. optimizer.onSuccessObservable.add(function () {
  96706. onSuccess();
  96707. });
  96708. }
  96709. if (onFailure) {
  96710. optimizer.onFailureObservable.add(function () {
  96711. onFailure();
  96712. });
  96713. }
  96714. optimizer.start();
  96715. return optimizer;
  96716. };
  96717. return SceneOptimizer;
  96718. }());
  96719. BABYLON.SceneOptimizer = SceneOptimizer;
  96720. })(BABYLON || (BABYLON = {}));
  96721. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  96722. var BABYLON;
  96723. (function (BABYLON) {
  96724. var OutlineRenderer = /** @class */ (function () {
  96725. function OutlineRenderer(scene) {
  96726. this.zOffset = 1;
  96727. this._scene = scene;
  96728. }
  96729. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  96730. var _this = this;
  96731. if (useOverlay === void 0) { useOverlay = false; }
  96732. var scene = this._scene;
  96733. var engine = this._scene.getEngine();
  96734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96735. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  96736. return;
  96737. }
  96738. var mesh = subMesh.getRenderingMesh();
  96739. var material = subMesh.getMaterial();
  96740. if (!material || !scene.activeCamera) {
  96741. return;
  96742. }
  96743. engine.enableEffect(this._effect);
  96744. // Logarithmic depth
  96745. if (material.useLogarithmicDepth) {
  96746. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  96747. }
  96748. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  96749. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  96750. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  96751. // Bones
  96752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96753. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96754. }
  96755. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  96756. // Alpha test
  96757. if (material && material.needAlphaTesting()) {
  96758. var alphaTexture = material.getAlphaTestTexture();
  96759. if (alphaTexture) {
  96760. this._effect.setTexture("diffuseSampler", alphaTexture);
  96761. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  96762. }
  96763. }
  96764. engine.setZOffset(-this.zOffset);
  96765. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  96766. engine.setZOffset(0);
  96767. };
  96768. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  96769. var defines = [];
  96770. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  96771. var mesh = subMesh.getMesh();
  96772. var material = subMesh.getMaterial();
  96773. if (material) {
  96774. // Alpha test
  96775. if (material.needAlphaTesting()) {
  96776. defines.push("#define ALPHATEST");
  96777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96778. attribs.push(BABYLON.VertexBuffer.UVKind);
  96779. defines.push("#define UV1");
  96780. }
  96781. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  96782. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96783. defines.push("#define UV2");
  96784. }
  96785. }
  96786. //Logarithmic depth
  96787. if (material.useLogarithmicDepth) {
  96788. defines.push("#define LOGARITHMICDEPTH");
  96789. }
  96790. }
  96791. // Bones
  96792. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96795. if (mesh.numBoneInfluencers > 4) {
  96796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96798. }
  96799. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96800. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  96801. }
  96802. else {
  96803. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96804. }
  96805. // Instances
  96806. if (useInstances) {
  96807. defines.push("#define INSTANCES");
  96808. attribs.push("world0");
  96809. attribs.push("world1");
  96810. attribs.push("world2");
  96811. attribs.push("world3");
  96812. }
  96813. // Get correct effect
  96814. var join = defines.join("\n");
  96815. if (this._cachedDefines !== join) {
  96816. this._cachedDefines = join;
  96817. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  96818. }
  96819. return this._effect.isReady();
  96820. };
  96821. return OutlineRenderer;
  96822. }());
  96823. BABYLON.OutlineRenderer = OutlineRenderer;
  96824. })(BABYLON || (BABYLON = {}));
  96825. //# sourceMappingURL=babylon.outlineRenderer.js.map
  96826. var BABYLON;
  96827. (function (BABYLON) {
  96828. var FaceAdjacencies = /** @class */ (function () {
  96829. function FaceAdjacencies() {
  96830. this.edges = new Array();
  96831. this.edgesConnectedCount = 0;
  96832. }
  96833. return FaceAdjacencies;
  96834. }());
  96835. var EdgesRenderer = /** @class */ (function () {
  96836. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  96837. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  96838. if (epsilon === void 0) { epsilon = 0.95; }
  96839. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  96840. this.edgesWidthScalerForOrthographic = 1000.0;
  96841. this.edgesWidthScalerForPerspective = 50.0;
  96842. this._linesPositions = new Array();
  96843. this._linesNormals = new Array();
  96844. this._linesIndices = new Array();
  96845. this._buffers = {};
  96846. this._checkVerticesInsteadOfIndices = false;
  96847. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  96848. this.isEnabled = true;
  96849. this._source = source;
  96850. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  96851. this._epsilon = epsilon;
  96852. this._prepareRessources();
  96853. this._generateEdgesLines();
  96854. }
  96855. EdgesRenderer.prototype._prepareRessources = function () {
  96856. if (this._lineShader) {
  96857. return;
  96858. }
  96859. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  96860. attributes: ["position", "normal"],
  96861. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96862. });
  96863. this._lineShader.disableDepthWrite = true;
  96864. this._lineShader.backFaceCulling = false;
  96865. };
  96866. EdgesRenderer.prototype._rebuild = function () {
  96867. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96868. if (buffer) {
  96869. buffer._rebuild();
  96870. }
  96871. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96872. if (buffer) {
  96873. buffer._rebuild();
  96874. }
  96875. var scene = this._source.getScene();
  96876. var engine = scene.getEngine();
  96877. this._ib = engine.createIndexBuffer(this._linesIndices);
  96878. };
  96879. EdgesRenderer.prototype.dispose = function () {
  96880. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96881. if (buffer) {
  96882. buffer.dispose();
  96883. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96884. }
  96885. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96886. if (buffer) {
  96887. buffer.dispose();
  96888. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96889. }
  96890. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96891. this._lineShader.dispose();
  96892. };
  96893. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96894. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96895. return 0;
  96896. }
  96897. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96898. return 1;
  96899. }
  96900. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96901. return 2;
  96902. }
  96903. return -1;
  96904. };
  96905. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96906. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96907. return 0;
  96908. }
  96909. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96910. return 1;
  96911. }
  96912. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96913. return 2;
  96914. }
  96915. return -1;
  96916. };
  96917. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96918. var needToCreateLine;
  96919. if (edge === undefined) {
  96920. needToCreateLine = true;
  96921. }
  96922. else {
  96923. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96924. needToCreateLine = dotProduct < this._epsilon;
  96925. }
  96926. if (needToCreateLine) {
  96927. var offset = this._linesPositions.length / 3;
  96928. var normal = p0.subtract(p1);
  96929. normal.normalize();
  96930. // Positions
  96931. this._linesPositions.push(p0.x);
  96932. this._linesPositions.push(p0.y);
  96933. this._linesPositions.push(p0.z);
  96934. this._linesPositions.push(p0.x);
  96935. this._linesPositions.push(p0.y);
  96936. this._linesPositions.push(p0.z);
  96937. this._linesPositions.push(p1.x);
  96938. this._linesPositions.push(p1.y);
  96939. this._linesPositions.push(p1.z);
  96940. this._linesPositions.push(p1.x);
  96941. this._linesPositions.push(p1.y);
  96942. this._linesPositions.push(p1.z);
  96943. // Normals
  96944. this._linesNormals.push(p1.x);
  96945. this._linesNormals.push(p1.y);
  96946. this._linesNormals.push(p1.z);
  96947. this._linesNormals.push(-1);
  96948. this._linesNormals.push(p1.x);
  96949. this._linesNormals.push(p1.y);
  96950. this._linesNormals.push(p1.z);
  96951. this._linesNormals.push(1);
  96952. this._linesNormals.push(p0.x);
  96953. this._linesNormals.push(p0.y);
  96954. this._linesNormals.push(p0.z);
  96955. this._linesNormals.push(-1);
  96956. this._linesNormals.push(p0.x);
  96957. this._linesNormals.push(p0.y);
  96958. this._linesNormals.push(p0.z);
  96959. this._linesNormals.push(1);
  96960. // Indices
  96961. this._linesIndices.push(offset);
  96962. this._linesIndices.push(offset + 1);
  96963. this._linesIndices.push(offset + 2);
  96964. this._linesIndices.push(offset);
  96965. this._linesIndices.push(offset + 2);
  96966. this._linesIndices.push(offset + 3);
  96967. }
  96968. };
  96969. EdgesRenderer.prototype._generateEdgesLines = function () {
  96970. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96971. var indices = this._source.getIndices();
  96972. if (!indices || !positions) {
  96973. return;
  96974. }
  96975. // First let's find adjacencies
  96976. var adjacencies = new Array();
  96977. var faceNormals = new Array();
  96978. var index;
  96979. var faceAdjacencies;
  96980. // Prepare faces
  96981. for (index = 0; index < indices.length; index += 3) {
  96982. faceAdjacencies = new FaceAdjacencies();
  96983. var p0Index = indices[index];
  96984. var p1Index = indices[index + 1];
  96985. var p2Index = indices[index + 2];
  96986. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96987. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96988. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96989. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96990. faceNormal.normalize();
  96991. faceNormals.push(faceNormal);
  96992. adjacencies.push(faceAdjacencies);
  96993. }
  96994. // Scan
  96995. for (index = 0; index < adjacencies.length; index++) {
  96996. faceAdjacencies = adjacencies[index];
  96997. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96998. var otherFaceAdjacencies = adjacencies[otherIndex];
  96999. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  97000. break;
  97001. }
  97002. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  97003. continue;
  97004. }
  97005. var otherP0 = indices[otherIndex * 3];
  97006. var otherP1 = indices[otherIndex * 3 + 1];
  97007. var otherP2 = indices[otherIndex * 3 + 2];
  97008. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  97009. var otherEdgeIndex = 0;
  97010. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  97011. continue;
  97012. }
  97013. switch (edgeIndex) {
  97014. case 0:
  97015. if (this._checkVerticesInsteadOfIndices) {
  97016. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97017. }
  97018. else {
  97019. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  97020. }
  97021. break;
  97022. case 1:
  97023. if (this._checkVerticesInsteadOfIndices) {
  97024. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97025. }
  97026. else {
  97027. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  97028. }
  97029. break;
  97030. case 2:
  97031. if (this._checkVerticesInsteadOfIndices) {
  97032. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  97033. }
  97034. else {
  97035. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  97036. }
  97037. break;
  97038. }
  97039. if (otherEdgeIndex === -1) {
  97040. continue;
  97041. }
  97042. faceAdjacencies.edges[edgeIndex] = otherIndex;
  97043. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  97044. faceAdjacencies.edgesConnectedCount++;
  97045. otherFaceAdjacencies.edgesConnectedCount++;
  97046. if (faceAdjacencies.edgesConnectedCount === 3) {
  97047. break;
  97048. }
  97049. }
  97050. }
  97051. }
  97052. // Create lines
  97053. for (index = 0; index < adjacencies.length; index++) {
  97054. // 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
  97055. var current = adjacencies[index];
  97056. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  97057. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  97058. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  97059. }
  97060. // Merge into a single mesh
  97061. var engine = this._source.getScene().getEngine();
  97062. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  97063. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  97064. this._ib = engine.createIndexBuffer(this._linesIndices);
  97065. this._indicesCount = this._linesIndices.length;
  97066. };
  97067. EdgesRenderer.prototype.render = function () {
  97068. var scene = this._source.getScene();
  97069. if (!this._lineShader.isReady() || !scene.activeCamera) {
  97070. return;
  97071. }
  97072. var engine = scene.getEngine();
  97073. this._lineShader._preBind();
  97074. // VBOs
  97075. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  97076. scene.resetCachedMaterial();
  97077. this._lineShader.setColor4("color", this._source.edgesColor);
  97078. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  97079. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  97080. }
  97081. else {
  97082. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  97083. }
  97084. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  97085. this._lineShader.bind(this._source.getWorldMatrix());
  97086. // Draw order
  97087. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  97088. this._lineShader.unbind();
  97089. engine.setDepthWrite(true);
  97090. };
  97091. return EdgesRenderer;
  97092. }());
  97093. BABYLON.EdgesRenderer = EdgesRenderer;
  97094. })(BABYLON || (BABYLON = {}));
  97095. //# sourceMappingURL=babylon.edgesRenderer.js.map
  97096. var BABYLON;
  97097. (function (BABYLON) {
  97098. // Adds the parser to the scene parsers.
  97099. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  97100. if (parsedData.effectLayers) {
  97101. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  97102. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  97103. container.effectLayers.push(effectLayer);
  97104. }
  97105. }
  97106. });
  97107. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  97108. var index = this.effectLayers.indexOf(toRemove);
  97109. if (index !== -1) {
  97110. this.effectLayers.splice(index, 1);
  97111. }
  97112. return index;
  97113. };
  97114. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  97115. this.effectLayers.push(newEffectLayer);
  97116. };
  97117. /**
  97118. * Defines the layer scene component responsible to manage any effect layers
  97119. * in a given scene.
  97120. */
  97121. var EffectLayerSceneComponent = /** @class */ (function () {
  97122. /**
  97123. * Creates a new instance of the component for the given scene
  97124. * @param scene Defines the scene to register the component in
  97125. */
  97126. function EffectLayerSceneComponent(scene) {
  97127. /**
  97128. * The component name helpfull to identify the component in the list of scene components.
  97129. */
  97130. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  97131. this._renderEffects = false;
  97132. this._needStencil = false;
  97133. this._previousStencilState = false;
  97134. this.scene = scene;
  97135. this._engine = scene.getEngine();
  97136. scene.effectLayers = new Array();
  97137. }
  97138. /**
  97139. * Registers the component in a given scene
  97140. */
  97141. EffectLayerSceneComponent.prototype.register = function () {
  97142. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  97143. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  97144. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  97145. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  97146. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  97147. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  97148. };
  97149. /**
  97150. * Rebuilds the elements related to this component in case of
  97151. * context lost for instance.
  97152. */
  97153. EffectLayerSceneComponent.prototype.rebuild = function () {
  97154. var layers = this.scene.effectLayers;
  97155. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  97156. var effectLayer = layers_1[_i];
  97157. effectLayer._rebuild();
  97158. }
  97159. };
  97160. /**
  97161. * Serializes the component data to the specified json object
  97162. * @param serializationObject The object to serialize to
  97163. */
  97164. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  97165. // Effect layers
  97166. serializationObject.effectLayers = [];
  97167. var layers = this.scene.effectLayers;
  97168. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  97169. var effectLayer = layers_2[_i];
  97170. if (effectLayer.serialize) {
  97171. serializationObject.effectLayers.push(effectLayer.serialize());
  97172. }
  97173. }
  97174. };
  97175. /**
  97176. * Adds all the element from the container to the scene
  97177. * @param container the container holding the elements
  97178. */
  97179. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  97180. var _this = this;
  97181. if (!container.effectLayers) {
  97182. return;
  97183. }
  97184. container.effectLayers.forEach(function (o) {
  97185. _this.scene.addEffectLayer(o);
  97186. });
  97187. };
  97188. /**
  97189. * Removes all the elements in the container from the scene
  97190. * @param container contains the elements to remove
  97191. */
  97192. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  97193. var _this = this;
  97194. if (!container.effectLayers) {
  97195. return;
  97196. }
  97197. container.effectLayers.forEach(function (o) {
  97198. _this.scene.removeEffectLayer(o);
  97199. });
  97200. };
  97201. /**
  97202. * Disposes the component and the associated ressources.
  97203. */
  97204. EffectLayerSceneComponent.prototype.dispose = function () {
  97205. var layers = this.scene.effectLayers;
  97206. while (layers.length) {
  97207. layers[0].dispose();
  97208. }
  97209. };
  97210. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  97211. var layers = this.scene.effectLayers;
  97212. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  97213. var layer = layers_3[_i];
  97214. if (!layer.hasMesh(mesh)) {
  97215. continue;
  97216. }
  97217. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  97218. var subMesh = _b[_a];
  97219. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  97220. return false;
  97221. }
  97222. }
  97223. }
  97224. return true;
  97225. };
  97226. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  97227. this._renderEffects = false;
  97228. this._needStencil = false;
  97229. var layers = this.scene.effectLayers;
  97230. if (layers && layers.length > 0) {
  97231. this._previousStencilState = this._engine.getStencilBuffer();
  97232. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  97233. var effectLayer = layers_4[_i];
  97234. if (effectLayer.shouldRender() &&
  97235. (!effectLayer.camera ||
  97236. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  97237. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  97238. this._renderEffects = true;
  97239. this._needStencil = this._needStencil || effectLayer.needStencil();
  97240. var renderTarget = effectLayer._mainTexture;
  97241. if (renderTarget._shouldRender()) {
  97242. this.scene.incrementRenderId();
  97243. renderTarget.render(false, false);
  97244. }
  97245. }
  97246. }
  97247. this.scene.incrementRenderId();
  97248. }
  97249. };
  97250. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  97251. // Activate effect Layer stencil
  97252. if (this._needStencil) {
  97253. this._engine.setStencilBuffer(true);
  97254. }
  97255. };
  97256. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  97257. // Restore effect Layer stencil
  97258. if (this._needStencil) {
  97259. this._engine.setStencilBuffer(this._previousStencilState);
  97260. }
  97261. };
  97262. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  97263. if (this._renderEffects) {
  97264. this._engine.setDepthBuffer(false);
  97265. var layers = this.scene.effectLayers;
  97266. for (var i = 0; i < layers.length; i++) {
  97267. var effectLayer = layers[i];
  97268. if (effectLayer.renderingGroupId === renderingGroupId) {
  97269. if (effectLayer.shouldRender()) {
  97270. effectLayer.render();
  97271. }
  97272. }
  97273. }
  97274. this._engine.setDepthBuffer(true);
  97275. }
  97276. };
  97277. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  97278. if (this._renderEffects) {
  97279. this._draw(-1);
  97280. }
  97281. };
  97282. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  97283. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  97284. this._draw(index);
  97285. }
  97286. };
  97287. return EffectLayerSceneComponent;
  97288. }());
  97289. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  97290. })(BABYLON || (BABYLON = {}));
  97291. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  97292. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97293. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97294. s = arguments[i];
  97295. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97296. t[p] = s[p];
  97297. }
  97298. return t;
  97299. };
  97300. var BABYLON;
  97301. (function (BABYLON) {
  97302. /**
  97303. * The effect layer Helps adding post process effect blended with the main pass.
  97304. *
  97305. * This can be for instance use to generate glow or higlight effects on the scene.
  97306. *
  97307. * The effect layer class can not be used directly and is intented to inherited from to be
  97308. * customized per effects.
  97309. */
  97310. var EffectLayer = /** @class */ (function () {
  97311. /**
  97312. * Instantiates a new effect Layer and references it in the scene.
  97313. * @param name The name of the layer
  97314. * @param scene The scene to use the layer in
  97315. */
  97316. function EffectLayer(
  97317. /** The Friendly of the effect in the scene */
  97318. name, scene) {
  97319. this._vertexBuffers = {};
  97320. this._maxSize = 0;
  97321. this._mainTextureDesiredSize = { width: 0, height: 0 };
  97322. this._shouldRender = true;
  97323. this._postProcesses = [];
  97324. this._textures = [];
  97325. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  97326. /**
  97327. * The clear color of the texture used to generate the glow map.
  97328. */
  97329. this.neutralColor = new BABYLON.Color4();
  97330. /**
  97331. * Specifies wether the highlight layer is enabled or not.
  97332. */
  97333. this.isEnabled = true;
  97334. /**
  97335. * An event triggered when the effect layer has been disposed.
  97336. */
  97337. this.onDisposeObservable = new BABYLON.Observable();
  97338. /**
  97339. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  97340. */
  97341. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  97342. /**
  97343. * An event triggered when the generated texture is being merged in the scene.
  97344. */
  97345. this.onBeforeComposeObservable = new BABYLON.Observable();
  97346. /**
  97347. * An event triggered when the generated texture has been merged in the scene.
  97348. */
  97349. this.onAfterComposeObservable = new BABYLON.Observable();
  97350. /**
  97351. * An event triggered when the efffect layer changes its size.
  97352. */
  97353. this.onSizeChangedObservable = new BABYLON.Observable();
  97354. this.name = name;
  97355. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97356. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  97357. if (!component) {
  97358. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  97359. this._scene._addComponent(component);
  97360. }
  97361. this._engine = this._scene.getEngine();
  97362. this._maxSize = this._engine.getCaps().maxTextureSize;
  97363. this._scene.effectLayers.push(this);
  97364. // Generate Buffers
  97365. this._generateIndexBuffer();
  97366. this._genrateVertexBuffer();
  97367. }
  97368. Object.defineProperty(EffectLayer.prototype, "camera", {
  97369. /**
  97370. * Gets the camera attached to the layer.
  97371. */
  97372. get: function () {
  97373. return this._effectLayerOptions.camera;
  97374. },
  97375. enumerable: true,
  97376. configurable: true
  97377. });
  97378. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  97379. /**
  97380. * Gets the rendering group id the layer should render in.
  97381. */
  97382. get: function () {
  97383. return this._effectLayerOptions.renderingGroupId;
  97384. },
  97385. enumerable: true,
  97386. configurable: true
  97387. });
  97388. /**
  97389. * Initializes the effect layer with the required options.
  97390. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  97391. */
  97392. EffectLayer.prototype._init = function (options) {
  97393. // Adapt options
  97394. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97395. this._setMainTextureSize();
  97396. this._createMainTexture();
  97397. this._createTextureAndPostProcesses();
  97398. this._mergeEffect = this._createMergeEffect();
  97399. };
  97400. /**
  97401. * Generates the index buffer of the full screen quad blending to the main canvas.
  97402. */
  97403. EffectLayer.prototype._generateIndexBuffer = function () {
  97404. // Indices
  97405. var indices = [];
  97406. indices.push(0);
  97407. indices.push(1);
  97408. indices.push(2);
  97409. indices.push(0);
  97410. indices.push(2);
  97411. indices.push(3);
  97412. this._indexBuffer = this._engine.createIndexBuffer(indices);
  97413. };
  97414. /**
  97415. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  97416. */
  97417. EffectLayer.prototype._genrateVertexBuffer = function () {
  97418. // VBO
  97419. var vertices = [];
  97420. vertices.push(1, 1);
  97421. vertices.push(-1, 1);
  97422. vertices.push(-1, -1);
  97423. vertices.push(1, -1);
  97424. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97425. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97426. };
  97427. /**
  97428. * Sets the main texture desired size which is the closest power of two
  97429. * of the engine canvas size.
  97430. */
  97431. EffectLayer.prototype._setMainTextureSize = function () {
  97432. if (this._effectLayerOptions.mainTextureFixedSize) {
  97433. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  97434. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  97435. }
  97436. else {
  97437. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  97438. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  97439. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  97440. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  97441. }
  97442. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  97443. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  97444. };
  97445. /**
  97446. * Creates the main texture for the effect layer.
  97447. */
  97448. EffectLayer.prototype._createMainTexture = function () {
  97449. var _this = this;
  97450. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  97451. width: this._mainTextureDesiredSize.width,
  97452. height: this._mainTextureDesiredSize.height
  97453. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97454. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  97455. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97456. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97457. this._mainTexture.anisotropicFilteringLevel = 1;
  97458. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97459. this._mainTexture.renderParticles = false;
  97460. this._mainTexture.renderList = null;
  97461. this._mainTexture.ignoreCameraViewport = true;
  97462. // Custom render function
  97463. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  97464. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  97465. var index;
  97466. var engine = _this._scene.getEngine();
  97467. if (depthOnlySubMeshes.length) {
  97468. engine.setColorWrite(false);
  97469. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  97470. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  97471. }
  97472. engine.setColorWrite(true);
  97473. }
  97474. for (index = 0; index < opaqueSubMeshes.length; index++) {
  97475. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  97476. }
  97477. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  97478. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  97479. }
  97480. for (index = 0; index < transparentSubMeshes.length; index++) {
  97481. _this._renderSubMesh(transparentSubMeshes.data[index]);
  97482. }
  97483. };
  97484. this._mainTexture.onClearObservable.add(function (engine) {
  97485. engine.clear(_this.neutralColor, true, true, true);
  97486. });
  97487. };
  97488. /**
  97489. * Checks for the readiness of the element composing the layer.
  97490. * @param subMesh the mesh to check for
  97491. * @param useInstances specify wether or not to use instances to render the mesh
  97492. * @param emissiveTexture the associated emissive texture used to generate the glow
  97493. * @return true if ready otherwise, false
  97494. */
  97495. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  97496. var material = subMesh.getMaterial();
  97497. if (!material) {
  97498. return false;
  97499. }
  97500. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  97501. return false;
  97502. }
  97503. var defines = [];
  97504. var attribs = [BABYLON.VertexBuffer.PositionKind];
  97505. var mesh = subMesh.getMesh();
  97506. var uv1 = false;
  97507. var uv2 = false;
  97508. // Alpha test
  97509. if (material && material.needAlphaTesting()) {
  97510. var alphaTexture = material.getAlphaTestTexture();
  97511. if (alphaTexture) {
  97512. defines.push("#define ALPHATEST");
  97513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97514. alphaTexture.coordinatesIndex === 1) {
  97515. defines.push("#define DIFFUSEUV2");
  97516. uv2 = true;
  97517. }
  97518. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97519. defines.push("#define DIFFUSEUV1");
  97520. uv1 = true;
  97521. }
  97522. }
  97523. }
  97524. // Emissive
  97525. if (emissiveTexture) {
  97526. defines.push("#define EMISSIVE");
  97527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  97528. emissiveTexture.coordinatesIndex === 1) {
  97529. defines.push("#define EMISSIVEUV2");
  97530. uv2 = true;
  97531. }
  97532. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  97533. defines.push("#define EMISSIVEUV1");
  97534. uv1 = true;
  97535. }
  97536. }
  97537. if (uv1) {
  97538. attribs.push(BABYLON.VertexBuffer.UVKind);
  97539. defines.push("#define UV1");
  97540. }
  97541. if (uv2) {
  97542. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  97543. defines.push("#define UV2");
  97544. }
  97545. // Bones
  97546. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  97547. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  97548. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  97549. if (mesh.numBoneInfluencers > 4) {
  97550. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  97551. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  97552. }
  97553. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  97554. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  97555. }
  97556. else {
  97557. defines.push("#define NUM_BONE_INFLUENCERS 0");
  97558. }
  97559. // Morph targets
  97560. var manager = mesh.morphTargetManager;
  97561. var morphInfluencers = 0;
  97562. if (manager) {
  97563. if (manager.numInfluencers > 0) {
  97564. defines.push("#define MORPHTARGETS");
  97565. morphInfluencers = manager.numInfluencers;
  97566. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  97567. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  97568. }
  97569. }
  97570. // Instances
  97571. if (useInstances) {
  97572. defines.push("#define INSTANCES");
  97573. attribs.push("world0");
  97574. attribs.push("world1");
  97575. attribs.push("world2");
  97576. attribs.push("world3");
  97577. }
  97578. // Get correct effect
  97579. var join = defines.join("\n");
  97580. if (this._cachedDefines !== join) {
  97581. this._cachedDefines = join;
  97582. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  97583. }
  97584. return this._effectLayerMapGenerationEffect.isReady();
  97585. };
  97586. /**
  97587. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  97588. */
  97589. EffectLayer.prototype.render = function () {
  97590. var currentEffect = this._mergeEffect;
  97591. // Check
  97592. if (!currentEffect.isReady())
  97593. return;
  97594. for (var i = 0; i < this._postProcesses.length; i++) {
  97595. if (!this._postProcesses[i].isReady()) {
  97596. return;
  97597. }
  97598. }
  97599. var engine = this._scene.getEngine();
  97600. this.onBeforeComposeObservable.notifyObservers(this);
  97601. // Render
  97602. engine.enableEffect(currentEffect);
  97603. engine.setState(false);
  97604. // VBOs
  97605. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97606. // Cache
  97607. var previousAlphaMode = engine.getAlphaMode();
  97608. // Go Blend.
  97609. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  97610. // Blends the map on the main canvas.
  97611. this._internalRender(currentEffect);
  97612. // Restore Alpha
  97613. engine.setAlphaMode(previousAlphaMode);
  97614. this.onAfterComposeObservable.notifyObservers(this);
  97615. // Handle size changes.
  97616. var size = this._mainTexture.getSize();
  97617. this._setMainTextureSize();
  97618. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  97619. // Recreate RTT and post processes on size change.
  97620. this.onSizeChangedObservable.notifyObservers(this);
  97621. this._disposeTextureAndPostProcesses();
  97622. this._createMainTexture();
  97623. this._createTextureAndPostProcesses();
  97624. }
  97625. };
  97626. /**
  97627. * Determine if a given mesh will be used in the current effect.
  97628. * @param mesh mesh to test
  97629. * @returns true if the mesh will be used
  97630. */
  97631. EffectLayer.prototype.hasMesh = function (mesh) {
  97632. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  97633. return true;
  97634. }
  97635. return false;
  97636. };
  97637. /**
  97638. * Returns true if the layer contains information to display, otherwise false.
  97639. * @returns true if the glow layer should be rendered
  97640. */
  97641. EffectLayer.prototype.shouldRender = function () {
  97642. return this.isEnabled && this._shouldRender;
  97643. };
  97644. /**
  97645. * Returns true if the mesh should render, otherwise false.
  97646. * @param mesh The mesh to render
  97647. * @returns true if it should render otherwise false
  97648. */
  97649. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  97650. return true;
  97651. };
  97652. /**
  97653. * Returns true if the mesh should render, otherwise false.
  97654. * @param mesh The mesh to render
  97655. * @returns true if it should render otherwise false
  97656. */
  97657. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  97658. return true;
  97659. };
  97660. /**
  97661. * Renders the submesh passed in parameter to the generation map.
  97662. */
  97663. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  97664. var _this = this;
  97665. if (!this.shouldRender()) {
  97666. return;
  97667. }
  97668. var material = subMesh.getMaterial();
  97669. var mesh = subMesh.getRenderingMesh();
  97670. var scene = this._scene;
  97671. var engine = scene.getEngine();
  97672. if (!material) {
  97673. return;
  97674. }
  97675. // Do not block in blend mode.
  97676. if (material.needAlphaBlendingForMesh(mesh)) {
  97677. return;
  97678. }
  97679. // Culling
  97680. engine.setState(material.backFaceCulling);
  97681. // Managing instances
  97682. var batch = mesh._getInstancesRenderList(subMesh._id);
  97683. if (batch.mustReturn) {
  97684. return;
  97685. }
  97686. // Early Exit per mesh
  97687. if (!this._shouldRenderMesh(mesh)) {
  97688. return;
  97689. }
  97690. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  97691. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  97692. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  97693. engine.enableEffect(this._effectLayerMapGenerationEffect);
  97694. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  97695. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  97696. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  97697. // Alpha test
  97698. if (material && material.needAlphaTesting()) {
  97699. var alphaTexture = material.getAlphaTestTexture();
  97700. if (alphaTexture) {
  97701. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  97702. var textureMatrix = alphaTexture.getTextureMatrix();
  97703. if (textureMatrix) {
  97704. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  97705. }
  97706. }
  97707. }
  97708. // Glow emissive only
  97709. if (this._emissiveTextureAndColor.texture) {
  97710. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  97711. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  97712. }
  97713. // Bones
  97714. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  97715. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  97716. }
  97717. // Morph targets
  97718. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  97719. // Draw
  97720. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  97721. }
  97722. else {
  97723. // Need to reset refresh rate of the main map
  97724. this._mainTexture.resetRefreshCounter();
  97725. }
  97726. };
  97727. /**
  97728. * Rebuild the required buffers.
  97729. * @hidden Internal use only.
  97730. */
  97731. EffectLayer.prototype._rebuild = function () {
  97732. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97733. if (vb) {
  97734. vb._rebuild();
  97735. }
  97736. this._generateIndexBuffer();
  97737. };
  97738. /**
  97739. * Dispose only the render target textures and post process.
  97740. */
  97741. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  97742. this._mainTexture.dispose();
  97743. for (var i = 0; i < this._postProcesses.length; i++) {
  97744. if (this._postProcesses[i]) {
  97745. this._postProcesses[i].dispose();
  97746. }
  97747. }
  97748. this._postProcesses = [];
  97749. for (var i = 0; i < this._textures.length; i++) {
  97750. if (this._textures[i]) {
  97751. this._textures[i].dispose();
  97752. }
  97753. }
  97754. this._textures = [];
  97755. };
  97756. /**
  97757. * Dispose the highlight layer and free resources.
  97758. */
  97759. EffectLayer.prototype.dispose = function () {
  97760. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97761. if (vertexBuffer) {
  97762. vertexBuffer.dispose();
  97763. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97764. }
  97765. if (this._indexBuffer) {
  97766. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97767. this._indexBuffer = null;
  97768. }
  97769. // Clean textures and post processes
  97770. this._disposeTextureAndPostProcesses();
  97771. // Remove from scene
  97772. var index = this._scene.effectLayers.indexOf(this, 0);
  97773. if (index > -1) {
  97774. this._scene.effectLayers.splice(index, 1);
  97775. }
  97776. // Callback
  97777. this.onDisposeObservable.notifyObservers(this);
  97778. this.onDisposeObservable.clear();
  97779. this.onBeforeRenderMainTextureObservable.clear();
  97780. this.onBeforeComposeObservable.clear();
  97781. this.onAfterComposeObservable.clear();
  97782. this.onSizeChangedObservable.clear();
  97783. };
  97784. /**
  97785. * Gets the class name of the effect layer
  97786. * @returns the string with the class name of the effect layer
  97787. */
  97788. EffectLayer.prototype.getClassName = function () {
  97789. return "EffectLayer";
  97790. };
  97791. /**
  97792. * Creates an effect layer from parsed effect layer data
  97793. * @param parsedEffectLayer defines effect layer data
  97794. * @param scene defines the current scene
  97795. * @param rootUrl defines the root URL containing the effect layer information
  97796. * @returns a parsed effect Layer
  97797. */
  97798. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  97799. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  97800. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  97801. };
  97802. __decorate([
  97803. BABYLON.serialize()
  97804. ], EffectLayer.prototype, "name", void 0);
  97805. __decorate([
  97806. BABYLON.serializeAsColor4()
  97807. ], EffectLayer.prototype, "neutralColor", void 0);
  97808. __decorate([
  97809. BABYLON.serialize()
  97810. ], EffectLayer.prototype, "isEnabled", void 0);
  97811. __decorate([
  97812. BABYLON.serializeAsCameraReference()
  97813. ], EffectLayer.prototype, "camera", null);
  97814. __decorate([
  97815. BABYLON.serialize()
  97816. ], EffectLayer.prototype, "renderingGroupId", null);
  97817. return EffectLayer;
  97818. }());
  97819. BABYLON.EffectLayer = EffectLayer;
  97820. })(BABYLON || (BABYLON = {}));
  97821. //# sourceMappingURL=babylon.effectLayer.js.map
  97822. var BABYLON;
  97823. (function (BABYLON) {
  97824. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  97825. for (var index = 0; index < this.effectLayers.length; index++) {
  97826. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  97827. return this.effectLayers[index];
  97828. }
  97829. }
  97830. return null;
  97831. };
  97832. /**
  97833. * Special Glow Blur post process only blurring the alpha channel
  97834. * It enforces keeping the most luminous color in the color channel.
  97835. */
  97836. var GlowBlurPostProcess = /** @class */ (function (_super) {
  97837. __extends(GlowBlurPostProcess, _super);
  97838. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  97839. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  97840. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  97841. _this.direction = direction;
  97842. _this.kernel = kernel;
  97843. _this.onApplyObservable.add(function (effect) {
  97844. effect.setFloat2("screenSize", _this.width, _this.height);
  97845. effect.setVector2("direction", _this.direction);
  97846. effect.setFloat("blurWidth", _this.kernel);
  97847. });
  97848. return _this;
  97849. }
  97850. return GlowBlurPostProcess;
  97851. }(BABYLON.PostProcess));
  97852. /**
  97853. * The highlight layer Helps adding a glow effect around a mesh.
  97854. *
  97855. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97856. * glowy meshes to your scene.
  97857. *
  97858. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  97859. */
  97860. var HighlightLayer = /** @class */ (function (_super) {
  97861. __extends(HighlightLayer, _super);
  97862. /**
  97863. * Instantiates a new highlight Layer and references it to the scene..
  97864. * @param name The name of the layer
  97865. * @param scene The scene to use the layer in
  97866. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97867. */
  97868. function HighlightLayer(name, scene, options) {
  97869. var _this = _super.call(this, name, scene) || this;
  97870. _this.name = name;
  97871. /**
  97872. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97873. */
  97874. _this.innerGlow = true;
  97875. /**
  97876. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97877. */
  97878. _this.outerGlow = true;
  97879. /**
  97880. * An event triggered when the highlight layer is being blurred.
  97881. */
  97882. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97883. /**
  97884. * An event triggered when the highlight layer has been blurred.
  97885. */
  97886. _this.onAfterBlurObservable = new BABYLON.Observable();
  97887. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97888. _this._meshes = {};
  97889. _this._excludedMeshes = {};
  97890. _this.neutralColor = HighlightLayer.NeutralColor;
  97891. // Warn on stencil
  97892. if (!_this._engine.isStencilEnable) {
  97893. 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 }");
  97894. }
  97895. // Adapt options
  97896. _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);
  97897. // Initialize the layer
  97898. _this._init({
  97899. alphaBlendingMode: _this._options.alphaBlendingMode,
  97900. camera: _this._options.camera,
  97901. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97902. mainTextureRatio: _this._options.mainTextureRatio,
  97903. renderingGroupId: _this._options.renderingGroupId
  97904. });
  97905. // Do not render as long as no meshes have been added
  97906. _this._shouldRender = false;
  97907. return _this;
  97908. }
  97909. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97910. /**
  97911. * Gets the horizontal size of the blur.
  97912. */
  97913. get: function () {
  97914. return this._horizontalBlurPostprocess.kernel;
  97915. },
  97916. /**
  97917. * Specifies the horizontal size of the blur.
  97918. */
  97919. set: function (value) {
  97920. this._horizontalBlurPostprocess.kernel = value;
  97921. },
  97922. enumerable: true,
  97923. configurable: true
  97924. });
  97925. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97926. /**
  97927. * Gets the vertical size of the blur.
  97928. */
  97929. get: function () {
  97930. return this._verticalBlurPostprocess.kernel;
  97931. },
  97932. /**
  97933. * Specifies the vertical size of the blur.
  97934. */
  97935. set: function (value) {
  97936. this._verticalBlurPostprocess.kernel = value;
  97937. },
  97938. enumerable: true,
  97939. configurable: true
  97940. });
  97941. /**
  97942. * Get the effect name of the layer.
  97943. * @return The effect name
  97944. */
  97945. HighlightLayer.prototype.getEffectName = function () {
  97946. return HighlightLayer.EffectName;
  97947. };
  97948. /**
  97949. * Create the merge effect. This is the shader use to blit the information back
  97950. * to the main canvas at the end of the scene rendering.
  97951. */
  97952. HighlightLayer.prototype._createMergeEffect = function () {
  97953. // Effect
  97954. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97955. };
  97956. /**
  97957. * Creates the render target textures and post processes used in the highlight layer.
  97958. */
  97959. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97960. var _this = this;
  97961. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97962. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97963. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97964. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97965. var textureType = 0;
  97966. if (this._engine.getCaps().textureHalfFloatRender) {
  97967. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97968. }
  97969. else {
  97970. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97971. }
  97972. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97973. width: blurTextureWidth,
  97974. height: blurTextureHeight
  97975. }, this._scene, false, true, textureType);
  97976. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97977. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97978. this._blurTexture.anisotropicFilteringLevel = 16;
  97979. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97980. this._blurTexture.renderParticles = false;
  97981. this._blurTexture.ignoreCameraViewport = true;
  97982. this._textures = [this._blurTexture];
  97983. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97984. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97985. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97986. effect.setTexture("textureSampler", _this._mainTexture);
  97987. });
  97988. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97989. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97990. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97991. });
  97992. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97993. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97994. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97995. });
  97996. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97997. }
  97998. else {
  97999. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  98000. width: blurTextureWidth,
  98001. height: blurTextureHeight
  98002. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98003. this._horizontalBlurPostprocess.width = blurTextureWidth;
  98004. this._horizontalBlurPostprocess.height = blurTextureHeight;
  98005. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  98006. effect.setTexture("textureSampler", _this._mainTexture);
  98007. });
  98008. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  98009. width: blurTextureWidth,
  98010. height: blurTextureHeight
  98011. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98012. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  98013. }
  98014. this._mainTexture.onAfterUnbindObservable.add(function () {
  98015. _this.onBeforeBlurObservable.notifyObservers(_this);
  98016. var internalTexture = _this._blurTexture.getInternalTexture();
  98017. if (internalTexture) {
  98018. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  98019. }
  98020. _this.onAfterBlurObservable.notifyObservers(_this);
  98021. });
  98022. // Prevent autoClear.
  98023. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98024. };
  98025. /**
  98026. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98027. */
  98028. HighlightLayer.prototype.needStencil = function () {
  98029. return true;
  98030. };
  98031. /**
  98032. * Checks for the readiness of the element composing the layer.
  98033. * @param subMesh the mesh to check for
  98034. * @param useInstances specify wether or not to use instances to render the mesh
  98035. * @param emissiveTexture the associated emissive texture used to generate the glow
  98036. * @return true if ready otherwise, false
  98037. */
  98038. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  98039. var material = subMesh.getMaterial();
  98040. var mesh = subMesh.getRenderingMesh();
  98041. if (!material || !mesh || !this._meshes) {
  98042. return false;
  98043. }
  98044. var emissiveTexture = null;
  98045. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98046. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98047. emissiveTexture = material.emissiveTexture;
  98048. }
  98049. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98050. };
  98051. /**
  98052. * Implementation specific of rendering the generating effect on the main canvas.
  98053. * @param effect The effect used to render through
  98054. */
  98055. HighlightLayer.prototype._internalRender = function (effect) {
  98056. // Texture
  98057. effect.setTexture("textureSampler", this._blurTexture);
  98058. // Cache
  98059. var engine = this._engine;
  98060. var previousStencilBuffer = engine.getStencilBuffer();
  98061. var previousStencilFunction = engine.getStencilFunction();
  98062. var previousStencilMask = engine.getStencilMask();
  98063. var previousStencilOperationPass = engine.getStencilOperationPass();
  98064. var previousStencilOperationFail = engine.getStencilOperationFail();
  98065. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  98066. var previousStencilReference = engine.getStencilFunctionReference();
  98067. // Stencil operations
  98068. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  98069. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  98070. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  98071. // Draw order
  98072. engine.setStencilMask(0x00);
  98073. engine.setStencilBuffer(true);
  98074. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  98075. // 2 passes inner outer
  98076. if (this.outerGlow) {
  98077. effect.setFloat("offset", 0);
  98078. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  98079. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98080. }
  98081. if (this.innerGlow) {
  98082. effect.setFloat("offset", 1);
  98083. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  98084. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98085. }
  98086. // Restore Cache
  98087. engine.setStencilFunction(previousStencilFunction);
  98088. engine.setStencilMask(previousStencilMask);
  98089. engine.setStencilBuffer(previousStencilBuffer);
  98090. engine.setStencilOperationPass(previousStencilOperationPass);
  98091. engine.setStencilOperationFail(previousStencilOperationFail);
  98092. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  98093. engine.setStencilFunctionReference(previousStencilReference);
  98094. };
  98095. /**
  98096. * Returns true if the layer contains information to display, otherwise false.
  98097. */
  98098. HighlightLayer.prototype.shouldRender = function () {
  98099. if (_super.prototype.shouldRender.call(this)) {
  98100. return this._meshes ? true : false;
  98101. }
  98102. return false;
  98103. };
  98104. /**
  98105. * Returns true if the mesh should render, otherwise false.
  98106. * @param mesh The mesh to render
  98107. * @returns true if it should render otherwise false
  98108. */
  98109. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  98110. // Excluded Mesh
  98111. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  98112. return false;
  98113. }
  98114. ;
  98115. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98116. return false;
  98117. }
  98118. return true;
  98119. };
  98120. /**
  98121. * Sets the required values for both the emissive texture and and the main color.
  98122. */
  98123. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98124. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  98125. if (highlightLayerMesh) {
  98126. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  98127. }
  98128. else {
  98129. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98130. }
  98131. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  98132. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98133. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  98134. }
  98135. else {
  98136. this._emissiveTextureAndColor.texture = null;
  98137. }
  98138. };
  98139. /**
  98140. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  98141. * @param mesh The mesh to exclude from the highlight layer
  98142. */
  98143. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  98144. if (!this._excludedMeshes) {
  98145. return;
  98146. }
  98147. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98148. if (!meshExcluded) {
  98149. this._excludedMeshes[mesh.uniqueId] = {
  98150. mesh: mesh,
  98151. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  98152. mesh.getEngine().setStencilBuffer(false);
  98153. }),
  98154. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  98155. mesh.getEngine().setStencilBuffer(true);
  98156. }),
  98157. };
  98158. }
  98159. };
  98160. /**
  98161. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  98162. * @param mesh The mesh to highlight
  98163. */
  98164. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  98165. if (!this._excludedMeshes) {
  98166. return;
  98167. }
  98168. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  98169. if (meshExcluded) {
  98170. if (meshExcluded.beforeRender) {
  98171. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  98172. }
  98173. if (meshExcluded.afterRender) {
  98174. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  98175. }
  98176. }
  98177. this._excludedMeshes[mesh.uniqueId] = null;
  98178. };
  98179. /**
  98180. * Determine if a given mesh will be highlighted by the current HighlightLayer
  98181. * @param mesh mesh to test
  98182. * @returns true if the mesh will be highlighted by the current HighlightLayer
  98183. */
  98184. HighlightLayer.prototype.hasMesh = function (mesh) {
  98185. if (!this._meshes) {
  98186. return false;
  98187. }
  98188. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98189. return false;
  98190. }
  98191. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  98192. };
  98193. /**
  98194. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  98195. * @param mesh The mesh to highlight
  98196. * @param color The color of the highlight
  98197. * @param glowEmissiveOnly Extract the glow from the emissive texture
  98198. */
  98199. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  98200. var _this = this;
  98201. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  98202. if (!this._meshes) {
  98203. return;
  98204. }
  98205. var meshHighlight = this._meshes[mesh.uniqueId];
  98206. if (meshHighlight) {
  98207. meshHighlight.color = color;
  98208. }
  98209. else {
  98210. this._meshes[mesh.uniqueId] = {
  98211. mesh: mesh,
  98212. color: color,
  98213. // Lambda required for capture due to Observable this context
  98214. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  98215. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  98216. _this._defaultStencilReference(mesh);
  98217. }
  98218. else {
  98219. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  98220. }
  98221. }),
  98222. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  98223. glowEmissiveOnly: glowEmissiveOnly
  98224. };
  98225. mesh.onDisposeObservable.add(function () {
  98226. _this._disposeMesh(mesh);
  98227. });
  98228. }
  98229. this._shouldRender = true;
  98230. };
  98231. /**
  98232. * Remove a mesh from the highlight layer in order to make it stop glowing.
  98233. * @param mesh The mesh to highlight
  98234. */
  98235. HighlightLayer.prototype.removeMesh = function (mesh) {
  98236. if (!this._meshes) {
  98237. return;
  98238. }
  98239. var meshHighlight = this._meshes[mesh.uniqueId];
  98240. if (meshHighlight) {
  98241. if (meshHighlight.observerHighlight) {
  98242. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98243. }
  98244. if (meshHighlight.observerDefault) {
  98245. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98246. }
  98247. delete this._meshes[mesh.uniqueId];
  98248. }
  98249. this._shouldRender = false;
  98250. for (var meshHighlightToCheck in this._meshes) {
  98251. if (this._meshes[meshHighlightToCheck]) {
  98252. this._shouldRender = true;
  98253. break;
  98254. }
  98255. }
  98256. };
  98257. /**
  98258. * Force the stencil to the normal expected value for none glowing parts
  98259. */
  98260. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  98261. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  98262. };
  98263. /**
  98264. * Free any resources and references associated to a mesh.
  98265. * Internal use
  98266. * @param mesh The mesh to free.
  98267. */
  98268. HighlightLayer.prototype._disposeMesh = function (mesh) {
  98269. this.removeMesh(mesh);
  98270. this.removeExcludedMesh(mesh);
  98271. };
  98272. /**
  98273. * Dispose the highlight layer and free resources.
  98274. */
  98275. HighlightLayer.prototype.dispose = function () {
  98276. if (this._meshes) {
  98277. // Clean mesh references
  98278. for (var id in this._meshes) {
  98279. var meshHighlight = this._meshes[id];
  98280. if (meshHighlight && meshHighlight.mesh) {
  98281. if (meshHighlight.observerHighlight) {
  98282. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  98283. }
  98284. if (meshHighlight.observerDefault) {
  98285. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  98286. }
  98287. }
  98288. }
  98289. this._meshes = null;
  98290. }
  98291. if (this._excludedMeshes) {
  98292. for (var id in this._excludedMeshes) {
  98293. var meshHighlight = this._excludedMeshes[id];
  98294. if (meshHighlight) {
  98295. if (meshHighlight.beforeRender) {
  98296. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  98297. }
  98298. if (meshHighlight.afterRender) {
  98299. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  98300. }
  98301. }
  98302. }
  98303. this._excludedMeshes = null;
  98304. }
  98305. _super.prototype.dispose.call(this);
  98306. };
  98307. /**
  98308. * Gets the class name of the effect layer
  98309. * @returns the string with the class name of the effect layer
  98310. */
  98311. HighlightLayer.prototype.getClassName = function () {
  98312. return "HighlightLayer";
  98313. };
  98314. /**
  98315. * Serializes this Highlight layer
  98316. * @returns a serialized Highlight layer object
  98317. */
  98318. HighlightLayer.prototype.serialize = function () {
  98319. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98320. serializationObject.customType = "BABYLON.HighlightLayer";
  98321. // Highlighted meshes
  98322. serializationObject.meshes = [];
  98323. if (this._meshes) {
  98324. for (var m in this._meshes) {
  98325. var mesh = this._meshes[m];
  98326. if (mesh) {
  98327. serializationObject.meshes.push({
  98328. glowEmissiveOnly: mesh.glowEmissiveOnly,
  98329. color: mesh.color.asArray(),
  98330. meshId: mesh.mesh.id
  98331. });
  98332. }
  98333. }
  98334. }
  98335. // Excluded meshes
  98336. serializationObject.excludedMeshes = [];
  98337. if (this._excludedMeshes) {
  98338. for (var e in this._excludedMeshes) {
  98339. var excludedMesh = this._excludedMeshes[e];
  98340. if (excludedMesh) {
  98341. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  98342. }
  98343. }
  98344. }
  98345. return serializationObject;
  98346. };
  98347. /**
  98348. * Creates a Highlight layer from parsed Highlight layer data
  98349. * @param parsedHightlightLayer defines the Highlight layer data
  98350. * @param scene defines the current scene
  98351. * @param rootUrl defines the root URL containing the Highlight layer information
  98352. * @returns a parsed Highlight layer
  98353. */
  98354. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  98355. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  98356. var index;
  98357. // Excluded meshes
  98358. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  98359. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  98360. if (mesh) {
  98361. hl.addExcludedMesh(mesh);
  98362. }
  98363. }
  98364. // Included meshes
  98365. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  98366. var highlightedMesh = parsedHightlightLayer.meshes[index];
  98367. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  98368. if (mesh) {
  98369. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  98370. }
  98371. }
  98372. return hl;
  98373. };
  98374. /**
  98375. * Effect Name of the highlight layer.
  98376. */
  98377. HighlightLayer.EffectName = "HighlightLayer";
  98378. /**
  98379. * The neutral color used during the preparation of the glow effect.
  98380. * This is black by default as the blend operation is a blend operation.
  98381. */
  98382. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  98383. /**
  98384. * Stencil value used for glowing meshes.
  98385. */
  98386. HighlightLayer.GlowingMeshStencilReference = 0x02;
  98387. /**
  98388. * Stencil value used for the other meshes in the scene.
  98389. */
  98390. HighlightLayer.NormalMeshStencilReference = 0x01;
  98391. __decorate([
  98392. BABYLON.serialize()
  98393. ], HighlightLayer.prototype, "innerGlow", void 0);
  98394. __decorate([
  98395. BABYLON.serialize()
  98396. ], HighlightLayer.prototype, "outerGlow", void 0);
  98397. __decorate([
  98398. BABYLON.serialize()
  98399. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  98400. __decorate([
  98401. BABYLON.serialize()
  98402. ], HighlightLayer.prototype, "blurVerticalSize", null);
  98403. __decorate([
  98404. BABYLON.serialize("options")
  98405. ], HighlightLayer.prototype, "_options", void 0);
  98406. return HighlightLayer;
  98407. }(BABYLON.EffectLayer));
  98408. BABYLON.HighlightLayer = HighlightLayer;
  98409. })(BABYLON || (BABYLON = {}));
  98410. //# sourceMappingURL=babylon.highlightLayer.js.map
  98411. var BABYLON;
  98412. (function (BABYLON) {
  98413. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  98414. for (var index = 0; index < this.effectLayers.length; index++) {
  98415. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  98416. return this.effectLayers[index];
  98417. }
  98418. }
  98419. return null;
  98420. };
  98421. /**
  98422. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  98423. *
  98424. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  98425. * glowy meshes to your scene.
  98426. *
  98427. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  98428. */
  98429. var GlowLayer = /** @class */ (function (_super) {
  98430. __extends(GlowLayer, _super);
  98431. /**
  98432. * Instantiates a new glow Layer and references it to the scene.
  98433. * @param name The name of the layer
  98434. * @param scene The scene to use the layer in
  98435. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  98436. */
  98437. function GlowLayer(name, scene, options) {
  98438. var _this = _super.call(this, name, scene) || this;
  98439. _this._intensity = 1.0;
  98440. _this._includedOnlyMeshes = [];
  98441. _this._excludedMeshes = [];
  98442. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  98443. // Adapt options
  98444. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  98445. // Initialize the layer
  98446. _this._init({
  98447. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  98448. camera: _this._options.camera,
  98449. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  98450. mainTextureRatio: _this._options.mainTextureRatio,
  98451. renderingGroupId: _this._options.renderingGroupId
  98452. });
  98453. return _this;
  98454. }
  98455. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  98456. /**
  98457. * Gets the kernel size of the blur.
  98458. */
  98459. get: function () {
  98460. return this._horizontalBlurPostprocess1.kernel;
  98461. },
  98462. /**
  98463. * Sets the kernel size of the blur.
  98464. */
  98465. set: function (value) {
  98466. this._horizontalBlurPostprocess1.kernel = value;
  98467. this._verticalBlurPostprocess1.kernel = value;
  98468. this._horizontalBlurPostprocess2.kernel = value;
  98469. this._verticalBlurPostprocess2.kernel = value;
  98470. },
  98471. enumerable: true,
  98472. configurable: true
  98473. });
  98474. Object.defineProperty(GlowLayer.prototype, "intensity", {
  98475. /**
  98476. * Gets the glow intensity.
  98477. */
  98478. get: function () {
  98479. return this._intensity;
  98480. },
  98481. /**
  98482. * Sets the glow intensity.
  98483. */
  98484. set: function (value) {
  98485. this._intensity = value;
  98486. },
  98487. enumerable: true,
  98488. configurable: true
  98489. });
  98490. /**
  98491. * Get the effect name of the layer.
  98492. * @return The effect name
  98493. */
  98494. GlowLayer.prototype.getEffectName = function () {
  98495. return GlowLayer.EffectName;
  98496. };
  98497. /**
  98498. * Create the merge effect. This is the shader use to blit the information back
  98499. * to the main canvas at the end of the scene rendering.
  98500. */
  98501. GlowLayer.prototype._createMergeEffect = function () {
  98502. // Effect
  98503. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  98504. };
  98505. /**
  98506. * Creates the render target textures and post processes used in the glow layer.
  98507. */
  98508. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  98509. var _this = this;
  98510. var blurTextureWidth = this._mainTextureDesiredSize.width;
  98511. var blurTextureHeight = this._mainTextureDesiredSize.height;
  98512. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  98513. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  98514. var textureType = 0;
  98515. if (this._engine.getCaps().textureHalfFloatRender) {
  98516. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98517. }
  98518. else {
  98519. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98520. }
  98521. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  98522. width: blurTextureWidth,
  98523. height: blurTextureHeight
  98524. }, this._scene, false, true, textureType);
  98525. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98526. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98527. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98528. this._blurTexture1.renderParticles = false;
  98529. this._blurTexture1.ignoreCameraViewport = true;
  98530. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  98531. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  98532. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  98533. width: blurTextureWidth2,
  98534. height: blurTextureHeight2
  98535. }, this._scene, false, true, textureType);
  98536. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98537. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98538. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98539. this._blurTexture2.renderParticles = false;
  98540. this._blurTexture2.ignoreCameraViewport = true;
  98541. this._textures = [this._blurTexture1, this._blurTexture2];
  98542. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98543. width: blurTextureWidth,
  98544. height: blurTextureHeight
  98545. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98546. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  98547. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  98548. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  98549. effect.setTexture("textureSampler", _this._mainTexture);
  98550. });
  98551. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98552. width: blurTextureWidth,
  98553. height: blurTextureHeight
  98554. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98555. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  98556. width: blurTextureWidth2,
  98557. height: blurTextureHeight2
  98558. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98559. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  98560. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  98561. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  98562. effect.setTexture("textureSampler", _this._blurTexture1);
  98563. });
  98564. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  98565. width: blurTextureWidth2,
  98566. height: blurTextureHeight2
  98567. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  98568. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98569. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  98570. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  98571. this._mainTexture.samples = this._options.mainTextureSamples;
  98572. this._mainTexture.onAfterUnbindObservable.add(function () {
  98573. var internalTexture = _this._blurTexture1.getInternalTexture();
  98574. if (internalTexture) {
  98575. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  98576. internalTexture = _this._blurTexture2.getInternalTexture();
  98577. if (internalTexture) {
  98578. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  98579. }
  98580. }
  98581. });
  98582. // Prevent autoClear.
  98583. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  98584. };
  98585. /**
  98586. * Checks for the readiness of the element composing the layer.
  98587. * @param subMesh the mesh to check for
  98588. * @param useInstances specify wether or not to use instances to render the mesh
  98589. * @param emissiveTexture the associated emissive texture used to generate the glow
  98590. * @return true if ready otherwise, false
  98591. */
  98592. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  98593. var material = subMesh.getMaterial();
  98594. var mesh = subMesh.getRenderingMesh();
  98595. if (!material || !mesh) {
  98596. return false;
  98597. }
  98598. var emissiveTexture = material.emissiveTexture;
  98599. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  98600. };
  98601. /**
  98602. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  98603. */
  98604. GlowLayer.prototype.needStencil = function () {
  98605. return false;
  98606. };
  98607. /**
  98608. * Implementation specific of rendering the generating effect on the main canvas.
  98609. * @param effect The effect used to render through
  98610. */
  98611. GlowLayer.prototype._internalRender = function (effect) {
  98612. // Texture
  98613. effect.setTexture("textureSampler", this._blurTexture1);
  98614. effect.setTexture("textureSampler2", this._blurTexture2);
  98615. effect.setFloat("offset", this._intensity);
  98616. // Cache
  98617. var engine = this._engine;
  98618. var previousStencilBuffer = engine.getStencilBuffer();
  98619. // Draw order
  98620. engine.setStencilBuffer(false);
  98621. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98622. // Draw order
  98623. engine.setStencilBuffer(previousStencilBuffer);
  98624. };
  98625. /**
  98626. * Sets the required values for both the emissive texture and and the main color.
  98627. */
  98628. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  98629. var textureLevel = 1.0;
  98630. if (this.customEmissiveTextureSelector) {
  98631. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  98632. }
  98633. else {
  98634. if (material) {
  98635. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  98636. if (this._emissiveTextureAndColor.texture) {
  98637. textureLevel = this._emissiveTextureAndColor.texture.level;
  98638. }
  98639. }
  98640. else {
  98641. this._emissiveTextureAndColor.texture = null;
  98642. }
  98643. }
  98644. if (this.customEmissiveColorSelector) {
  98645. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  98646. }
  98647. else {
  98648. if (material.emissiveColor) {
  98649. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  98650. }
  98651. else {
  98652. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  98653. }
  98654. }
  98655. };
  98656. /**
  98657. * Returns true if the mesh should render, otherwise false.
  98658. * @param mesh The mesh to render
  98659. * @returns true if it should render otherwise false
  98660. */
  98661. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  98662. return this.hasMesh(mesh);
  98663. };
  98664. /**
  98665. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  98666. * @param mesh The mesh to exclude from the glow layer
  98667. */
  98668. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  98669. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  98670. this._excludedMeshes.push(mesh.uniqueId);
  98671. }
  98672. };
  98673. /**
  98674. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  98675. * @param mesh The mesh to remove
  98676. */
  98677. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  98678. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  98679. if (index !== -1) {
  98680. this._excludedMeshes.splice(index, 1);
  98681. }
  98682. };
  98683. /**
  98684. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  98685. * @param mesh The mesh to include in the glow layer
  98686. */
  98687. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  98688. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  98689. this._includedOnlyMeshes.push(mesh.uniqueId);
  98690. }
  98691. };
  98692. /**
  98693. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  98694. * @param mesh The mesh to remove
  98695. */
  98696. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  98697. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  98698. if (index !== -1) {
  98699. this._includedOnlyMeshes.splice(index, 1);
  98700. }
  98701. };
  98702. /**
  98703. * Determine if a given mesh will be used in the glow layer
  98704. * @param mesh The mesh to test
  98705. * @returns true if the mesh will be highlighted by the current glow layer
  98706. */
  98707. GlowLayer.prototype.hasMesh = function (mesh) {
  98708. if (!_super.prototype.hasMesh.call(this, mesh)) {
  98709. return false;
  98710. }
  98711. // Included Mesh
  98712. if (this._includedOnlyMeshes.length) {
  98713. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  98714. }
  98715. ;
  98716. // Excluded Mesh
  98717. if (this._excludedMeshes.length) {
  98718. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  98719. }
  98720. ;
  98721. return true;
  98722. };
  98723. /**
  98724. * Free any resources and references associated to a mesh.
  98725. * Internal use
  98726. * @param mesh The mesh to free.
  98727. */
  98728. GlowLayer.prototype._disposeMesh = function (mesh) {
  98729. this.removeIncludedOnlyMesh(mesh);
  98730. this.removeExcludedMesh(mesh);
  98731. };
  98732. /**
  98733. * Gets the class name of the effect layer
  98734. * @returns the string with the class name of the effect layer
  98735. */
  98736. GlowLayer.prototype.getClassName = function () {
  98737. return "GlowLayer";
  98738. };
  98739. /**
  98740. * Serializes this glow layer
  98741. * @returns a serialized glow layer object
  98742. */
  98743. GlowLayer.prototype.serialize = function () {
  98744. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  98745. serializationObject.customType = "BABYLON.GlowLayer";
  98746. var index;
  98747. // Included meshes
  98748. serializationObject.includedMeshes = [];
  98749. if (this._includedOnlyMeshes.length) {
  98750. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  98751. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  98752. if (mesh) {
  98753. serializationObject.includedMeshes.push(mesh.id);
  98754. }
  98755. }
  98756. }
  98757. // Excluded meshes
  98758. serializationObject.excludedMeshes = [];
  98759. if (this._excludedMeshes.length) {
  98760. for (index = 0; index < this._excludedMeshes.length; index++) {
  98761. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  98762. if (mesh) {
  98763. serializationObject.excludedMeshes.push(mesh.id);
  98764. }
  98765. }
  98766. }
  98767. return serializationObject;
  98768. };
  98769. /**
  98770. * Creates a Glow Layer from parsed glow layer data
  98771. * @param parsedGlowLayer defines glow layer data
  98772. * @param scene defines the current scene
  98773. * @param rootUrl defines the root URL containing the glow layer information
  98774. * @returns a parsed Glow Layer
  98775. */
  98776. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  98777. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  98778. var index;
  98779. // Excluded meshes
  98780. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  98781. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  98782. if (mesh) {
  98783. gl.addExcludedMesh(mesh);
  98784. }
  98785. }
  98786. // Included meshes
  98787. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  98788. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  98789. if (mesh) {
  98790. gl.addIncludedOnlyMesh(mesh);
  98791. }
  98792. }
  98793. return gl;
  98794. };
  98795. /**
  98796. * Effect Name of the layer.
  98797. */
  98798. GlowLayer.EffectName = "GlowLayer";
  98799. /**
  98800. * The default blur kernel size used for the glow.
  98801. */
  98802. GlowLayer.DefaultBlurKernelSize = 32;
  98803. /**
  98804. * The default texture size ratio used for the glow.
  98805. */
  98806. GlowLayer.DefaultTextureRatio = 0.5;
  98807. __decorate([
  98808. BABYLON.serialize()
  98809. ], GlowLayer.prototype, "blurKernelSize", null);
  98810. __decorate([
  98811. BABYLON.serialize()
  98812. ], GlowLayer.prototype, "intensity", null);
  98813. __decorate([
  98814. BABYLON.serialize("options")
  98815. ], GlowLayer.prototype, "_options", void 0);
  98816. return GlowLayer;
  98817. }(BABYLON.EffectLayer));
  98818. BABYLON.GlowLayer = GlowLayer;
  98819. })(BABYLON || (BABYLON = {}));
  98820. //# sourceMappingURL=babylon.glowLayer.js.map
  98821. var BABYLON;
  98822. (function (BABYLON) {
  98823. /**
  98824. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  98825. */
  98826. var AssetTaskState;
  98827. (function (AssetTaskState) {
  98828. /**
  98829. * Initialization
  98830. */
  98831. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  98832. /**
  98833. * Running
  98834. */
  98835. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  98836. /**
  98837. * Done
  98838. */
  98839. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  98840. /**
  98841. * Error
  98842. */
  98843. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  98844. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  98845. /**
  98846. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  98847. */
  98848. var AbstractAssetTask = /** @class */ (function () {
  98849. /**
  98850. * Creates a new {BABYLON.AssetsManager}
  98851. * @param name defines the name of the task
  98852. */
  98853. function AbstractAssetTask(
  98854. /**
  98855. * Task name
  98856. */ name) {
  98857. this.name = name;
  98858. this._isCompleted = false;
  98859. this._taskState = AssetTaskState.INIT;
  98860. }
  98861. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98862. /**
  98863. * Get if the task is completed
  98864. */
  98865. get: function () {
  98866. return this._isCompleted;
  98867. },
  98868. enumerable: true,
  98869. configurable: true
  98870. });
  98871. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98872. /**
  98873. * Gets the current state of the task
  98874. */
  98875. get: function () {
  98876. return this._taskState;
  98877. },
  98878. enumerable: true,
  98879. configurable: true
  98880. });
  98881. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98882. /**
  98883. * Gets the current error object (if task is in error)
  98884. */
  98885. get: function () {
  98886. return this._errorObject;
  98887. },
  98888. enumerable: true,
  98889. configurable: true
  98890. });
  98891. /**
  98892. * Internal only
  98893. * @hidden
  98894. */
  98895. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98896. if (this._errorObject) {
  98897. return;
  98898. }
  98899. this._errorObject = {
  98900. message: message,
  98901. exception: exception
  98902. };
  98903. };
  98904. /**
  98905. * Execute the current task
  98906. * @param scene defines the scene where you want your assets to be loaded
  98907. * @param onSuccess is a callback called when the task is successfully executed
  98908. * @param onError is a callback called if an error occurs
  98909. */
  98910. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98911. var _this = this;
  98912. this._taskState = AssetTaskState.RUNNING;
  98913. this.runTask(scene, function () {
  98914. _this.onDoneCallback(onSuccess, onError);
  98915. }, function (msg, exception) {
  98916. _this.onErrorCallback(onError, msg, exception);
  98917. });
  98918. };
  98919. /**
  98920. * Execute the current task
  98921. * @param scene defines the scene where you want your assets to be loaded
  98922. * @param onSuccess is a callback called when the task is successfully executed
  98923. * @param onError is a callback called if an error occurs
  98924. */
  98925. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98926. throw new Error("runTask is not implemented");
  98927. };
  98928. /**
  98929. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98930. * This can be used with failed tasks that have the reason for failure fixed.
  98931. */
  98932. AbstractAssetTask.prototype.reset = function () {
  98933. this._taskState = AssetTaskState.INIT;
  98934. };
  98935. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98936. this._taskState = AssetTaskState.ERROR;
  98937. this._errorObject = {
  98938. message: message,
  98939. exception: exception
  98940. };
  98941. if (this.onError) {
  98942. this.onError(this, message, exception);
  98943. }
  98944. onError();
  98945. };
  98946. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98947. try {
  98948. this._taskState = AssetTaskState.DONE;
  98949. this._isCompleted = true;
  98950. if (this.onSuccess) {
  98951. this.onSuccess(this);
  98952. }
  98953. onSuccess();
  98954. }
  98955. catch (e) {
  98956. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98957. }
  98958. };
  98959. return AbstractAssetTask;
  98960. }());
  98961. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98962. /**
  98963. * Class used to share progress information about assets loading
  98964. */
  98965. var AssetsProgressEvent = /** @class */ (function () {
  98966. /**
  98967. * Creates a {BABYLON.AssetsProgressEvent}
  98968. * @param remainingCount defines the number of remaining tasks to process
  98969. * @param totalCount defines the total number of tasks
  98970. * @param task defines the task that was just processed
  98971. */
  98972. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98973. this.remainingCount = remainingCount;
  98974. this.totalCount = totalCount;
  98975. this.task = task;
  98976. }
  98977. return AssetsProgressEvent;
  98978. }());
  98979. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98980. /**
  98981. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98982. */
  98983. var MeshAssetTask = /** @class */ (function (_super) {
  98984. __extends(MeshAssetTask, _super);
  98985. /**
  98986. * Creates a new {BABYLON.MeshAssetTask}
  98987. * @param name defines the name of the task
  98988. * @param meshesNames defines the list of mesh's names you want to load
  98989. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98990. * @param sceneFilename defines the filename of the scene to load from
  98991. */
  98992. function MeshAssetTask(
  98993. /**
  98994. * Defines the name of the task
  98995. */
  98996. name,
  98997. /**
  98998. * Defines the list of mesh's names you want to load
  98999. */
  99000. meshesNames,
  99001. /**
  99002. * Defines the root url to use as a base to load your meshes and associated resources
  99003. */
  99004. rootUrl,
  99005. /**
  99006. * Defines the filename of the scene to load from
  99007. */
  99008. sceneFilename) {
  99009. var _this = _super.call(this, name) || this;
  99010. _this.name = name;
  99011. _this.meshesNames = meshesNames;
  99012. _this.rootUrl = rootUrl;
  99013. _this.sceneFilename = sceneFilename;
  99014. return _this;
  99015. }
  99016. /**
  99017. * Execute the current task
  99018. * @param scene defines the scene where you want your assets to be loaded
  99019. * @param onSuccess is a callback called when the task is successfully executed
  99020. * @param onError is a callback called if an error occurs
  99021. */
  99022. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99023. var _this = this;
  99024. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  99025. _this.loadedMeshes = meshes;
  99026. _this.loadedParticleSystems = particleSystems;
  99027. _this.loadedSkeletons = skeletons;
  99028. onSuccess();
  99029. }, null, function (scene, message, exception) {
  99030. onError(message, exception);
  99031. });
  99032. };
  99033. return MeshAssetTask;
  99034. }(AbstractAssetTask));
  99035. BABYLON.MeshAssetTask = MeshAssetTask;
  99036. /**
  99037. * Define a task used by {BABYLON.AssetsManager} to load text content
  99038. */
  99039. var TextFileAssetTask = /** @class */ (function (_super) {
  99040. __extends(TextFileAssetTask, _super);
  99041. /**
  99042. * Creates a new TextFileAssetTask object
  99043. * @param name defines the name of the task
  99044. * @param url defines the location of the file to load
  99045. */
  99046. function TextFileAssetTask(
  99047. /**
  99048. * Defines the name of the task
  99049. */
  99050. name,
  99051. /**
  99052. * Defines the location of the file to load
  99053. */
  99054. url) {
  99055. var _this = _super.call(this, name) || this;
  99056. _this.name = name;
  99057. _this.url = url;
  99058. return _this;
  99059. }
  99060. /**
  99061. * Execute the current task
  99062. * @param scene defines the scene where you want your assets to be loaded
  99063. * @param onSuccess is a callback called when the task is successfully executed
  99064. * @param onError is a callback called if an error occurs
  99065. */
  99066. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99067. var _this = this;
  99068. scene._loadFile(this.url, function (data) {
  99069. _this.text = data;
  99070. onSuccess();
  99071. }, undefined, false, false, function (request, exception) {
  99072. if (request) {
  99073. onError(request.status + " " + request.statusText, exception);
  99074. }
  99075. });
  99076. };
  99077. return TextFileAssetTask;
  99078. }(AbstractAssetTask));
  99079. BABYLON.TextFileAssetTask = TextFileAssetTask;
  99080. /**
  99081. * Define a task used by {BABYLON.AssetsManager} to load binary data
  99082. */
  99083. var BinaryFileAssetTask = /** @class */ (function (_super) {
  99084. __extends(BinaryFileAssetTask, _super);
  99085. /**
  99086. * Creates a new BinaryFileAssetTask object
  99087. * @param name defines the name of the new task
  99088. * @param url defines the location of the file to load
  99089. */
  99090. function BinaryFileAssetTask(
  99091. /**
  99092. * Defines the name of the task
  99093. */
  99094. name,
  99095. /**
  99096. * Defines the location of the file to load
  99097. */
  99098. url) {
  99099. var _this = _super.call(this, name) || this;
  99100. _this.name = name;
  99101. _this.url = url;
  99102. return _this;
  99103. }
  99104. /**
  99105. * Execute the current task
  99106. * @param scene defines the scene where you want your assets to be loaded
  99107. * @param onSuccess is a callback called when the task is successfully executed
  99108. * @param onError is a callback called if an error occurs
  99109. */
  99110. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99111. var _this = this;
  99112. scene._loadFile(this.url, function (data) {
  99113. _this.data = data;
  99114. onSuccess();
  99115. }, undefined, true, true, function (request, exception) {
  99116. if (request) {
  99117. onError(request.status + " " + request.statusText, exception);
  99118. }
  99119. });
  99120. };
  99121. return BinaryFileAssetTask;
  99122. }(AbstractAssetTask));
  99123. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  99124. /**
  99125. * Define a task used by {BABYLON.AssetsManager} to load images
  99126. */
  99127. var ImageAssetTask = /** @class */ (function (_super) {
  99128. __extends(ImageAssetTask, _super);
  99129. /**
  99130. * Creates a new ImageAssetTask
  99131. * @param name defines the name of the task
  99132. * @param url defines the location of the image to load
  99133. */
  99134. function ImageAssetTask(
  99135. /**
  99136. * Defines the name of the task
  99137. */
  99138. name,
  99139. /**
  99140. * Defines the location of the image to load
  99141. */
  99142. url) {
  99143. var _this = _super.call(this, name) || this;
  99144. _this.name = name;
  99145. _this.url = url;
  99146. return _this;
  99147. }
  99148. /**
  99149. * Execute the current task
  99150. * @param scene defines the scene where you want your assets to be loaded
  99151. * @param onSuccess is a callback called when the task is successfully executed
  99152. * @param onError is a callback called if an error occurs
  99153. */
  99154. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99155. var _this = this;
  99156. var img = new Image();
  99157. BABYLON.Tools.SetCorsBehavior(this.url, img);
  99158. img.onload = function () {
  99159. _this.image = img;
  99160. onSuccess();
  99161. };
  99162. img.onerror = function (err) {
  99163. onError("Error loading image", err);
  99164. };
  99165. img.src = this.url;
  99166. };
  99167. return ImageAssetTask;
  99168. }(AbstractAssetTask));
  99169. BABYLON.ImageAssetTask = ImageAssetTask;
  99170. /**
  99171. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  99172. */
  99173. var TextureAssetTask = /** @class */ (function (_super) {
  99174. __extends(TextureAssetTask, _super);
  99175. /**
  99176. * Creates a new TextureAssetTask object
  99177. * @param name defines the name of the task
  99178. * @param url defines the location of the file to load
  99179. * @param noMipmap defines if mipmap should not be generated (default is false)
  99180. * @param invertY defines if texture must be inverted on Y axis (default is false)
  99181. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99182. */
  99183. function TextureAssetTask(
  99184. /**
  99185. * Defines the name of the task
  99186. */
  99187. name,
  99188. /**
  99189. * Defines the location of the file to load
  99190. */
  99191. url,
  99192. /**
  99193. * Defines if mipmap should not be generated (default is false)
  99194. */
  99195. noMipmap,
  99196. /**
  99197. * Defines if texture must be inverted on Y axis (default is false)
  99198. */
  99199. invertY,
  99200. /**
  99201. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  99202. */
  99203. samplingMode) {
  99204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99205. var _this = _super.call(this, name) || this;
  99206. _this.name = name;
  99207. _this.url = url;
  99208. _this.noMipmap = noMipmap;
  99209. _this.invertY = invertY;
  99210. _this.samplingMode = samplingMode;
  99211. return _this;
  99212. }
  99213. /**
  99214. * Execute the current task
  99215. * @param scene defines the scene where you want your assets to be loaded
  99216. * @param onSuccess is a callback called when the task is successfully executed
  99217. * @param onError is a callback called if an error occurs
  99218. */
  99219. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99220. var onload = function () {
  99221. onSuccess();
  99222. };
  99223. var onerror = function (message, exception) {
  99224. onError(message, exception);
  99225. };
  99226. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  99227. };
  99228. return TextureAssetTask;
  99229. }(AbstractAssetTask));
  99230. BABYLON.TextureAssetTask = TextureAssetTask;
  99231. /**
  99232. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  99233. */
  99234. var CubeTextureAssetTask = /** @class */ (function (_super) {
  99235. __extends(CubeTextureAssetTask, _super);
  99236. /**
  99237. * Creates a new CubeTextureAssetTask
  99238. * @param name defines the name of the task
  99239. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99240. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99241. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99242. * @param files defines the explicit list of files (undefined by default)
  99243. */
  99244. function CubeTextureAssetTask(
  99245. /**
  99246. * Defines the name of the task
  99247. */
  99248. name,
  99249. /**
  99250. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  99251. */
  99252. url,
  99253. /**
  99254. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  99255. */
  99256. extensions,
  99257. /**
  99258. * Defines if mipmaps should not be generated (default is false)
  99259. */
  99260. noMipmap,
  99261. /**
  99262. * Defines the explicit list of files (undefined by default)
  99263. */
  99264. files) {
  99265. var _this = _super.call(this, name) || this;
  99266. _this.name = name;
  99267. _this.url = url;
  99268. _this.extensions = extensions;
  99269. _this.noMipmap = noMipmap;
  99270. _this.files = files;
  99271. return _this;
  99272. }
  99273. /**
  99274. * Execute the current task
  99275. * @param scene defines the scene where you want your assets to be loaded
  99276. * @param onSuccess is a callback called when the task is successfully executed
  99277. * @param onError is a callback called if an error occurs
  99278. */
  99279. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  99280. var onload = function () {
  99281. onSuccess();
  99282. };
  99283. var onerror = function (message, exception) {
  99284. onError(message, exception);
  99285. };
  99286. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  99287. };
  99288. return CubeTextureAssetTask;
  99289. }(AbstractAssetTask));
  99290. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  99291. /**
  99292. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  99293. */
  99294. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  99295. __extends(HDRCubeTextureAssetTask, _super);
  99296. /**
  99297. * Creates a new HDRCubeTextureAssetTask object
  99298. * @param name defines the name of the task
  99299. * @param url defines the location of the file to load
  99300. * @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.
  99301. * @param noMipmap defines if mipmaps should not be generated (default is false)
  99302. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99303. * @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)
  99304. * @param reserved Internal use only
  99305. */
  99306. function HDRCubeTextureAssetTask(
  99307. /**
  99308. * Defines the name of the task
  99309. */
  99310. name,
  99311. /**
  99312. * Defines the location of the file to load
  99313. */
  99314. url,
  99315. /**
  99316. * Defines the desired size (the more it increases the longer the generation will be)
  99317. */
  99318. size,
  99319. /**
  99320. * Defines if mipmaps should not be generated (default is false)
  99321. */
  99322. noMipmap,
  99323. /**
  99324. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  99325. */
  99326. generateHarmonics,
  99327. /**
  99328. * 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)
  99329. */
  99330. gammaSpace,
  99331. /**
  99332. * Internal Use Only
  99333. */
  99334. reserved) {
  99335. if (noMipmap === void 0) { noMipmap = false; }
  99336. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99337. if (gammaSpace === void 0) { gammaSpace = false; }
  99338. if (reserved === void 0) { reserved = false; }
  99339. var _this = _super.call(this, name) || this;
  99340. _this.name = name;
  99341. _this.url = url;
  99342. _this.size = size;
  99343. _this.noMipmap = noMipmap;
  99344. _this.generateHarmonics = generateHarmonics;
  99345. _this.gammaSpace = gammaSpace;
  99346. _this.reserved = reserved;
  99347. return _this;
  99348. }
  99349. /**
  99350. * Execute the current task
  99351. * @param scene defines the scene where you want your assets to be loaded
  99352. * @param onSuccess is a callback called when the task is successfully executed
  99353. * @param onError is a callback called if an error occurs
  99354. */
  99355. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  99356. var onload = function () {
  99357. onSuccess();
  99358. };
  99359. var onerror = function (message, exception) {
  99360. onError(message, exception);
  99361. };
  99362. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  99363. };
  99364. return HDRCubeTextureAssetTask;
  99365. }(AbstractAssetTask));
  99366. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  99367. /**
  99368. * This class can be used to easily import assets into a scene
  99369. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  99370. */
  99371. var AssetsManager = /** @class */ (function () {
  99372. /**
  99373. * Creates a new AssetsManager
  99374. * @param scene defines the scene to work on
  99375. */
  99376. function AssetsManager(scene) {
  99377. this._isLoading = false;
  99378. this._tasks = new Array();
  99379. this._waitingTasksCount = 0;
  99380. this._totalTasksCount = 0;
  99381. /**
  99382. * Observable called when all tasks are processed
  99383. */
  99384. this.onTaskSuccessObservable = new BABYLON.Observable();
  99385. /**
  99386. * Observable called when a task had an error
  99387. */
  99388. this.onTaskErrorObservable = new BABYLON.Observable();
  99389. /**
  99390. * Observable called when a task is successful
  99391. */
  99392. this.onTasksDoneObservable = new BABYLON.Observable();
  99393. /**
  99394. * Observable called when a task is done (whatever the result is)
  99395. */
  99396. this.onProgressObservable = new BABYLON.Observable();
  99397. /**
  99398. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  99399. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  99400. */
  99401. this.useDefaultLoadingScreen = true;
  99402. this._scene = scene;
  99403. }
  99404. /**
  99405. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  99406. * @param taskName defines the name of the new task
  99407. * @param meshesNames defines the name of meshes to load
  99408. * @param rootUrl defines the root url to use to locate files
  99409. * @param sceneFilename defines the filename of the scene file
  99410. * @returns a new {BABYLON.MeshAssetTask} object
  99411. */
  99412. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  99413. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  99414. this._tasks.push(task);
  99415. return task;
  99416. };
  99417. /**
  99418. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  99419. * @param taskName defines the name of the new task
  99420. * @param url defines the url of the file to load
  99421. * @returns a new {BABYLON.TextFileAssetTask} object
  99422. */
  99423. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  99424. var task = new TextFileAssetTask(taskName, url);
  99425. this._tasks.push(task);
  99426. return task;
  99427. };
  99428. /**
  99429. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  99430. * @param taskName defines the name of the new task
  99431. * @param url defines the url of the file to load
  99432. * @returns a new {BABYLON.BinaryFileAssetTask} object
  99433. */
  99434. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  99435. var task = new BinaryFileAssetTask(taskName, url);
  99436. this._tasks.push(task);
  99437. return task;
  99438. };
  99439. /**
  99440. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  99441. * @param taskName defines the name of the new task
  99442. * @param url defines the url of the file to load
  99443. * @returns a new {BABYLON.ImageAssetTask} object
  99444. */
  99445. AssetsManager.prototype.addImageTask = function (taskName, url) {
  99446. var task = new ImageAssetTask(taskName, url);
  99447. this._tasks.push(task);
  99448. return task;
  99449. };
  99450. /**
  99451. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  99452. * @param taskName defines the name of the new task
  99453. * @param url defines the url of the file to load
  99454. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99455. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  99456. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  99457. * @returns a new {BABYLON.TextureAssetTask} object
  99458. */
  99459. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  99460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99461. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  99462. this._tasks.push(task);
  99463. return task;
  99464. };
  99465. /**
  99466. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  99467. * @param taskName defines the name of the new task
  99468. * @param url defines the url of the file to load
  99469. * @param extensions defines the extension to use to load the cube map (can be null)
  99470. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99471. * @param files defines the list of files to load (can be null)
  99472. * @returns a new {BABYLON.CubeTextureAssetTask} object
  99473. */
  99474. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  99475. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  99476. this._tasks.push(task);
  99477. return task;
  99478. };
  99479. /**
  99480. *
  99481. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  99482. * @param taskName defines the name of the new task
  99483. * @param url defines the url of the file to load
  99484. * @param size defines the size you want for the cubemap (can be null)
  99485. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  99486. * @param generateHarmonics defines if you want to automatically generate (true by default)
  99487. * @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)
  99488. * @param reserved Internal use only
  99489. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  99490. */
  99491. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  99492. if (noMipmap === void 0) { noMipmap = false; }
  99493. if (generateHarmonics === void 0) { generateHarmonics = true; }
  99494. if (gammaSpace === void 0) { gammaSpace = false; }
  99495. if (reserved === void 0) { reserved = false; }
  99496. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  99497. this._tasks.push(task);
  99498. return task;
  99499. };
  99500. /**
  99501. * Remove a task from the assets manager.
  99502. * @param task the task to remove
  99503. */
  99504. AssetsManager.prototype.removeTask = function (task) {
  99505. var index = this._tasks.indexOf(task);
  99506. if (index > -1) {
  99507. this._tasks.splice(index, 1);
  99508. }
  99509. };
  99510. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  99511. this._waitingTasksCount--;
  99512. try {
  99513. if (this.onProgress) {
  99514. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  99515. }
  99516. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  99517. }
  99518. catch (e) {
  99519. BABYLON.Tools.Error("Error running progress callbacks.");
  99520. console.log(e);
  99521. }
  99522. if (this._waitingTasksCount === 0) {
  99523. try {
  99524. if (this.onFinish) {
  99525. this.onFinish(this._tasks);
  99526. }
  99527. // Let's remove successfull tasks
  99528. var currentTasks = this._tasks.slice();
  99529. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  99530. var task = currentTasks_1[_i];
  99531. if (task.taskState === AssetTaskState.DONE) {
  99532. var index = this._tasks.indexOf(task);
  99533. if (index > -1) {
  99534. this._tasks.splice(index, 1);
  99535. }
  99536. }
  99537. }
  99538. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99539. }
  99540. catch (e) {
  99541. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  99542. console.log(e);
  99543. }
  99544. this._isLoading = false;
  99545. this._scene.getEngine().hideLoadingUI();
  99546. }
  99547. };
  99548. AssetsManager.prototype._runTask = function (task) {
  99549. var _this = this;
  99550. var done = function () {
  99551. try {
  99552. if (_this.onTaskSuccess) {
  99553. _this.onTaskSuccess(task);
  99554. }
  99555. _this.onTaskSuccessObservable.notifyObservers(task);
  99556. _this._decreaseWaitingTasksCount(task);
  99557. }
  99558. catch (e) {
  99559. error("Error executing task success callbacks", e);
  99560. }
  99561. };
  99562. var error = function (message, exception) {
  99563. task._setErrorObject(message, exception);
  99564. if (_this.onTaskError) {
  99565. _this.onTaskError(task);
  99566. }
  99567. _this.onTaskErrorObservable.notifyObservers(task);
  99568. _this._decreaseWaitingTasksCount(task);
  99569. };
  99570. task.run(this._scene, done, error);
  99571. };
  99572. /**
  99573. * Reset the {BABYLON.AssetsManager} and remove all tasks
  99574. * @return the current instance of the {BABYLON.AssetsManager}
  99575. */
  99576. AssetsManager.prototype.reset = function () {
  99577. this._isLoading = false;
  99578. this._tasks = new Array();
  99579. return this;
  99580. };
  99581. /**
  99582. * Start the loading process
  99583. * @return the current instance of the {BABYLON.AssetsManager}
  99584. */
  99585. AssetsManager.prototype.load = function () {
  99586. if (this._isLoading) {
  99587. return this;
  99588. }
  99589. this._isLoading = true;
  99590. this._waitingTasksCount = this._tasks.length;
  99591. this._totalTasksCount = this._tasks.length;
  99592. if (this._waitingTasksCount === 0) {
  99593. this._isLoading = false;
  99594. if (this.onFinish) {
  99595. this.onFinish(this._tasks);
  99596. }
  99597. this.onTasksDoneObservable.notifyObservers(this._tasks);
  99598. return this;
  99599. }
  99600. if (this.useDefaultLoadingScreen) {
  99601. this._scene.getEngine().displayLoadingUI();
  99602. }
  99603. for (var index = 0; index < this._tasks.length; index++) {
  99604. var task = this._tasks[index];
  99605. if (task.taskState === AssetTaskState.INIT) {
  99606. this._runTask(task);
  99607. }
  99608. }
  99609. return this;
  99610. };
  99611. return AssetsManager;
  99612. }());
  99613. BABYLON.AssetsManager = AssetsManager;
  99614. })(BABYLON || (BABYLON = {}));
  99615. //# sourceMappingURL=babylon.assetsManager.js.map
  99616. var BABYLON;
  99617. (function (BABYLON) {
  99618. var serializedGeometries = [];
  99619. var serializeGeometry = function (geometry, serializationGeometries) {
  99620. if (serializedGeometries[geometry.id]) {
  99621. return;
  99622. }
  99623. if (geometry.doNotSerialize) {
  99624. return;
  99625. }
  99626. if (geometry instanceof BABYLON.BoxGeometry) {
  99627. serializationGeometries.boxes.push(geometry.serialize());
  99628. }
  99629. else if (geometry instanceof BABYLON.SphereGeometry) {
  99630. serializationGeometries.spheres.push(geometry.serialize());
  99631. }
  99632. else if (geometry instanceof BABYLON.CylinderGeometry) {
  99633. serializationGeometries.cylinders.push(geometry.serialize());
  99634. }
  99635. else if (geometry instanceof BABYLON.TorusGeometry) {
  99636. serializationGeometries.toruses.push(geometry.serialize());
  99637. }
  99638. else if (geometry instanceof BABYLON.GroundGeometry) {
  99639. serializationGeometries.grounds.push(geometry.serialize());
  99640. }
  99641. else if (geometry instanceof BABYLON.Plane) {
  99642. serializationGeometries.planes.push(geometry.serialize());
  99643. }
  99644. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  99645. serializationGeometries.torusKnots.push(geometry.serialize());
  99646. }
  99647. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  99648. throw new Error("Unknown primitive type");
  99649. }
  99650. else {
  99651. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  99652. }
  99653. serializedGeometries[geometry.id] = true;
  99654. };
  99655. var serializeMesh = function (mesh, serializationScene) {
  99656. var serializationObject = {};
  99657. // Geometry
  99658. var geometry = mesh._geometry;
  99659. if (geometry) {
  99660. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  99661. // 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
  99662. serializeGeometry(geometry, serializationScene.geometries);
  99663. }
  99664. }
  99665. // Custom
  99666. if (mesh.serialize) {
  99667. mesh.serialize(serializationObject);
  99668. }
  99669. return serializationObject;
  99670. };
  99671. var finalizeSingleMesh = function (mesh, serializationObject) {
  99672. //only works if the mesh is already loaded
  99673. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99674. //serialize material
  99675. if (mesh.material) {
  99676. if (mesh.material instanceof BABYLON.MultiMaterial) {
  99677. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  99678. serializationObject.materials = serializationObject.materials || [];
  99679. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99680. serializationObject.multiMaterials.push(mesh.material.serialize());
  99681. var _loop_1 = function (submaterial) {
  99682. if (submaterial) {
  99683. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  99684. serializationObject.materials.push(submaterial.serialize());
  99685. }
  99686. }
  99687. };
  99688. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  99689. var submaterial = _a[_i];
  99690. _loop_1(submaterial);
  99691. }
  99692. }
  99693. }
  99694. else {
  99695. serializationObject.materials = serializationObject.materials || [];
  99696. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  99697. serializationObject.materials.push(mesh.material.serialize());
  99698. }
  99699. }
  99700. }
  99701. //serialize geometry
  99702. var geometry = mesh._geometry;
  99703. if (geometry) {
  99704. if (!serializationObject.geometries) {
  99705. serializationObject.geometries = {};
  99706. serializationObject.geometries.boxes = [];
  99707. serializationObject.geometries.spheres = [];
  99708. serializationObject.geometries.cylinders = [];
  99709. serializationObject.geometries.toruses = [];
  99710. serializationObject.geometries.grounds = [];
  99711. serializationObject.geometries.planes = [];
  99712. serializationObject.geometries.torusKnots = [];
  99713. serializationObject.geometries.vertexData = [];
  99714. }
  99715. serializeGeometry(geometry, serializationObject.geometries);
  99716. }
  99717. // Skeletons
  99718. if (mesh.skeleton) {
  99719. serializationObject.skeletons = serializationObject.skeletons || [];
  99720. serializationObject.skeletons.push(mesh.skeleton.serialize());
  99721. }
  99722. //serialize the actual mesh
  99723. serializationObject.meshes = serializationObject.meshes || [];
  99724. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99725. }
  99726. };
  99727. var SceneSerializer = /** @class */ (function () {
  99728. function SceneSerializer() {
  99729. }
  99730. SceneSerializer.ClearCache = function () {
  99731. serializedGeometries = [];
  99732. };
  99733. SceneSerializer.Serialize = function (scene) {
  99734. var serializationObject = {};
  99735. SceneSerializer.ClearCache();
  99736. // Scene
  99737. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  99738. serializationObject.autoClear = scene.autoClear;
  99739. serializationObject.clearColor = scene.clearColor.asArray();
  99740. serializationObject.ambientColor = scene.ambientColor.asArray();
  99741. serializationObject.gravity = scene.gravity.asArray();
  99742. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  99743. serializationObject.workerCollisions = scene.workerCollisions;
  99744. // Fog
  99745. if (scene.fogMode && scene.fogMode !== 0) {
  99746. serializationObject.fogMode = scene.fogMode;
  99747. serializationObject.fogColor = scene.fogColor.asArray();
  99748. serializationObject.fogStart = scene.fogStart;
  99749. serializationObject.fogEnd = scene.fogEnd;
  99750. serializationObject.fogDensity = scene.fogDensity;
  99751. }
  99752. //Physics
  99753. if (scene.isPhysicsEnabled()) {
  99754. var physicEngine = scene.getPhysicsEngine();
  99755. if (physicEngine) {
  99756. serializationObject.physicsEnabled = true;
  99757. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  99758. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  99759. }
  99760. }
  99761. // Metadata
  99762. if (scene.metadata) {
  99763. serializationObject.metadata = scene.metadata;
  99764. }
  99765. // Morph targets
  99766. serializationObject.morphTargetManagers = [];
  99767. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  99768. var abstractMesh = _a[_i];
  99769. var manager = abstractMesh.morphTargetManager;
  99770. if (manager) {
  99771. serializationObject.morphTargetManagers.push(manager.serialize());
  99772. }
  99773. }
  99774. // Lights
  99775. serializationObject.lights = [];
  99776. var index;
  99777. var light;
  99778. for (index = 0; index < scene.lights.length; index++) {
  99779. light = scene.lights[index];
  99780. if (!light.doNotSerialize) {
  99781. serializationObject.lights.push(light.serialize());
  99782. }
  99783. }
  99784. // Cameras
  99785. serializationObject.cameras = [];
  99786. for (index = 0; index < scene.cameras.length; index++) {
  99787. var camera = scene.cameras[index];
  99788. if (!camera.doNotSerialize) {
  99789. serializationObject.cameras.push(camera.serialize());
  99790. }
  99791. }
  99792. if (scene.activeCamera) {
  99793. serializationObject.activeCameraID = scene.activeCamera.id;
  99794. }
  99795. // Animations
  99796. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  99797. // Materials
  99798. serializationObject.materials = [];
  99799. serializationObject.multiMaterials = [];
  99800. var material;
  99801. for (index = 0; index < scene.materials.length; index++) {
  99802. material = scene.materials[index];
  99803. if (!material.doNotSerialize) {
  99804. serializationObject.materials.push(material.serialize());
  99805. }
  99806. }
  99807. // MultiMaterials
  99808. serializationObject.multiMaterials = [];
  99809. for (index = 0; index < scene.multiMaterials.length; index++) {
  99810. var multiMaterial = scene.multiMaterials[index];
  99811. serializationObject.multiMaterials.push(multiMaterial.serialize());
  99812. }
  99813. // Environment texture
  99814. if (scene.environmentTexture) {
  99815. serializationObject.environmentTexture = scene.environmentTexture.name;
  99816. }
  99817. // Skeletons
  99818. serializationObject.skeletons = [];
  99819. for (index = 0; index < scene.skeletons.length; index++) {
  99820. var skeleton = scene.skeletons[index];
  99821. if (!skeleton.doNotSerialize) {
  99822. serializationObject.skeletons.push(skeleton.serialize());
  99823. }
  99824. }
  99825. // Transform nodes
  99826. serializationObject.transformNodes = [];
  99827. for (index = 0; index < scene.transformNodes.length; index++) {
  99828. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  99829. }
  99830. // Geometries
  99831. serializationObject.geometries = {};
  99832. serializationObject.geometries.boxes = [];
  99833. serializationObject.geometries.spheres = [];
  99834. serializationObject.geometries.cylinders = [];
  99835. serializationObject.geometries.toruses = [];
  99836. serializationObject.geometries.grounds = [];
  99837. serializationObject.geometries.planes = [];
  99838. serializationObject.geometries.torusKnots = [];
  99839. serializationObject.geometries.vertexData = [];
  99840. serializedGeometries = [];
  99841. var geometries = scene.getGeometries();
  99842. for (index = 0; index < geometries.length; index++) {
  99843. var geometry = geometries[index];
  99844. if (geometry.isReady()) {
  99845. serializeGeometry(geometry, serializationObject.geometries);
  99846. }
  99847. }
  99848. // Meshes
  99849. serializationObject.meshes = [];
  99850. for (index = 0; index < scene.meshes.length; index++) {
  99851. var abstractMesh = scene.meshes[index];
  99852. if (abstractMesh instanceof BABYLON.Mesh) {
  99853. var mesh = abstractMesh;
  99854. if (!mesh.doNotSerialize) {
  99855. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  99856. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  99857. }
  99858. }
  99859. }
  99860. }
  99861. // Particles Systems
  99862. serializationObject.particleSystems = [];
  99863. for (index = 0; index < scene.particleSystems.length; index++) {
  99864. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  99865. }
  99866. // Shadows
  99867. serializationObject.shadowGenerators = [];
  99868. for (index = 0; index < scene.lights.length; index++) {
  99869. light = scene.lights[index];
  99870. var shadowGenerator = light.getShadowGenerator();
  99871. if (shadowGenerator) {
  99872. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  99873. }
  99874. }
  99875. // Action Manager
  99876. if (scene.actionManager) {
  99877. serializationObject.actions = scene.actionManager.serialize("scene");
  99878. }
  99879. // Audio
  99880. serializationObject.sounds = [];
  99881. for (index = 0; index < scene.soundTracks.length; index++) {
  99882. var soundtrack = scene.soundTracks[index];
  99883. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99884. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99885. }
  99886. }
  99887. // Components
  99888. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99889. var component = _c[_b];
  99890. component.serialize(serializationObject);
  99891. }
  99892. return serializationObject;
  99893. };
  99894. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99895. if (withParents === void 0) { withParents = false; }
  99896. if (withChildren === void 0) { withChildren = false; }
  99897. var serializationObject = {};
  99898. SceneSerializer.ClearCache();
  99899. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99900. if (withParents || withChildren) {
  99901. //deliberate for loop! not for each, appended should be processed as well.
  99902. for (var i = 0; i < toSerialize.length; ++i) {
  99903. if (withChildren) {
  99904. toSerialize[i].getDescendants().forEach(function (node) {
  99905. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99906. toSerialize.push(node);
  99907. }
  99908. });
  99909. }
  99910. //make sure the array doesn't contain the object already
  99911. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99912. toSerialize.push(toSerialize[i].parent);
  99913. }
  99914. }
  99915. }
  99916. toSerialize.forEach(function (mesh) {
  99917. finalizeSingleMesh(mesh, serializationObject);
  99918. });
  99919. return serializationObject;
  99920. };
  99921. return SceneSerializer;
  99922. }());
  99923. BABYLON.SceneSerializer = SceneSerializer;
  99924. })(BABYLON || (BABYLON = {}));
  99925. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99926. var BABYLON;
  99927. (function (BABYLON) {
  99928. var ReflectionProbe = /** @class */ (function () {
  99929. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99930. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99931. var _this = this;
  99932. this.name = name;
  99933. this._viewMatrix = BABYLON.Matrix.Identity();
  99934. this._target = BABYLON.Vector3.Zero();
  99935. this._add = BABYLON.Vector3.Zero();
  99936. this._invertYAxis = false;
  99937. this.position = BABYLON.Vector3.Zero();
  99938. this._scene = scene;
  99939. this._scene.reflectionProbes.push(this);
  99940. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99941. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99942. switch (faceIndex) {
  99943. case 0:
  99944. _this._add.copyFromFloats(1, 0, 0);
  99945. break;
  99946. case 1:
  99947. _this._add.copyFromFloats(-1, 0, 0);
  99948. break;
  99949. case 2:
  99950. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99951. break;
  99952. case 3:
  99953. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99954. break;
  99955. case 4:
  99956. _this._add.copyFromFloats(0, 0, 1);
  99957. break;
  99958. case 5:
  99959. _this._add.copyFromFloats(0, 0, -1);
  99960. break;
  99961. }
  99962. if (_this._attachedMesh) {
  99963. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99964. }
  99965. _this.position.addToRef(_this._add, _this._target);
  99966. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99967. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99968. scene._forcedViewPosition = _this.position;
  99969. });
  99970. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99971. scene._forcedViewPosition = null;
  99972. scene.updateTransformMatrix(true);
  99973. });
  99974. if (scene.activeCamera) {
  99975. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99976. }
  99977. }
  99978. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99979. get: function () {
  99980. return this._renderTargetTexture.samples;
  99981. },
  99982. set: function (value) {
  99983. this._renderTargetTexture.samples = value;
  99984. },
  99985. enumerable: true,
  99986. configurable: true
  99987. });
  99988. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99989. get: function () {
  99990. return this._renderTargetTexture.refreshRate;
  99991. },
  99992. set: function (value) {
  99993. this._renderTargetTexture.refreshRate = value;
  99994. },
  99995. enumerable: true,
  99996. configurable: true
  99997. });
  99998. ReflectionProbe.prototype.getScene = function () {
  99999. return this._scene;
  100000. };
  100001. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  100002. get: function () {
  100003. return this._renderTargetTexture;
  100004. },
  100005. enumerable: true,
  100006. configurable: true
  100007. });
  100008. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  100009. get: function () {
  100010. return this._renderTargetTexture.renderList;
  100011. },
  100012. enumerable: true,
  100013. configurable: true
  100014. });
  100015. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  100016. this._attachedMesh = mesh;
  100017. };
  100018. /**
  100019. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  100020. *
  100021. * @param renderingGroupId The rendering group id corresponding to its index
  100022. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  100023. */
  100024. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  100025. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  100026. };
  100027. ReflectionProbe.prototype.dispose = function () {
  100028. var index = this._scene.reflectionProbes.indexOf(this);
  100029. if (index !== -1) {
  100030. // Remove from the scene if found
  100031. this._scene.reflectionProbes.splice(index, 1);
  100032. }
  100033. if (this._renderTargetTexture) {
  100034. this._renderTargetTexture.dispose();
  100035. this._renderTargetTexture = null;
  100036. }
  100037. };
  100038. return ReflectionProbe;
  100039. }());
  100040. BABYLON.ReflectionProbe = ReflectionProbe;
  100041. })(BABYLON || (BABYLON = {}));
  100042. //# sourceMappingURL=babylon.reflectionProbe.js.map
  100043. var BABYLON;
  100044. (function (BABYLON) {
  100045. /**
  100046. * Defines the layer scene component responsible to manage any layers
  100047. * in a given scene.
  100048. */
  100049. var LayerSceneComponent = /** @class */ (function () {
  100050. /**
  100051. * Creates a new instance of the component for the given scene
  100052. * @param scene Defines the scene to register the component in
  100053. */
  100054. function LayerSceneComponent(scene) {
  100055. /**
  100056. * The component name helpfull to identify the component in the list of scene components.
  100057. */
  100058. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  100059. this.scene = scene;
  100060. this._engine = scene.getEngine();
  100061. scene.layers = new Array();
  100062. }
  100063. /**
  100064. * Registers the component in a given scene
  100065. */
  100066. LayerSceneComponent.prototype.register = function () {
  100067. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  100068. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  100069. };
  100070. /**
  100071. * Rebuilds the elements related to this component in case of
  100072. * context lost for instance.
  100073. */
  100074. LayerSceneComponent.prototype.rebuild = function () {
  100075. var layers = this.scene.layers;
  100076. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  100077. var layer = layers_1[_i];
  100078. layer._rebuild();
  100079. }
  100080. };
  100081. /**
  100082. * Disposes the component and the associated ressources.
  100083. */
  100084. LayerSceneComponent.prototype.dispose = function () {
  100085. var layers = this.scene.layers;
  100086. while (layers.length) {
  100087. layers[0].dispose();
  100088. }
  100089. };
  100090. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  100091. var layers = this.scene.layers;
  100092. if (layers.length) {
  100093. this._engine.setDepthBuffer(false);
  100094. var cameraLayerMask = camera.layerMask;
  100095. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  100096. var layer = layers_2[_i];
  100097. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  100098. layer.render();
  100099. }
  100100. }
  100101. this._engine.setDepthBuffer(true);
  100102. }
  100103. };
  100104. LayerSceneComponent.prototype._drawBackground = function (camera) {
  100105. this._draw(camera, true);
  100106. };
  100107. LayerSceneComponent.prototype._drawForeground = function (camera) {
  100108. this._draw(camera, false);
  100109. };
  100110. return LayerSceneComponent;
  100111. }());
  100112. BABYLON.LayerSceneComponent = LayerSceneComponent;
  100113. })(BABYLON || (BABYLON = {}));
  100114. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  100115. var BABYLON;
  100116. (function (BABYLON) {
  100117. var Layer = /** @class */ (function () {
  100118. function Layer(name, imgUrl, scene, isBackground, color) {
  100119. this.name = name;
  100120. this.scale = new BABYLON.Vector2(1, 1);
  100121. this.offset = new BABYLON.Vector2(0, 0);
  100122. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  100123. this.layerMask = 0x0FFFFFFF;
  100124. this._vertexBuffers = {};
  100125. // Events
  100126. /**
  100127. * An event triggered when the layer is disposed.
  100128. */
  100129. this.onDisposeObservable = new BABYLON.Observable();
  100130. /**
  100131. * An event triggered before rendering the scene
  100132. */
  100133. this.onBeforeRenderObservable = new BABYLON.Observable();
  100134. /**
  100135. * An event triggered after rendering the scene
  100136. */
  100137. this.onAfterRenderObservable = new BABYLON.Observable();
  100138. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  100139. this.isBackground = isBackground === undefined ? true : isBackground;
  100140. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  100141. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  100142. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  100143. if (!layerComponent) {
  100144. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  100145. this._scene._addComponent(layerComponent);
  100146. }
  100147. this._scene.layers.push(this);
  100148. var engine = this._scene.getEngine();
  100149. // VBO
  100150. var vertices = [];
  100151. vertices.push(1, 1);
  100152. vertices.push(-1, 1);
  100153. vertices.push(-1, -1);
  100154. vertices.push(1, -1);
  100155. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  100156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  100157. this._createIndexBuffer();
  100158. // Effects
  100159. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  100160. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  100161. }
  100162. Object.defineProperty(Layer.prototype, "onDispose", {
  100163. set: function (callback) {
  100164. if (this._onDisposeObserver) {
  100165. this.onDisposeObservable.remove(this._onDisposeObserver);
  100166. }
  100167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100168. },
  100169. enumerable: true,
  100170. configurable: true
  100171. });
  100172. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  100173. set: function (callback) {
  100174. if (this._onBeforeRenderObserver) {
  100175. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100176. }
  100177. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  100178. },
  100179. enumerable: true,
  100180. configurable: true
  100181. });
  100182. Object.defineProperty(Layer.prototype, "onAfterRender", {
  100183. set: function (callback) {
  100184. if (this._onAfterRenderObserver) {
  100185. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100186. }
  100187. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  100188. },
  100189. enumerable: true,
  100190. configurable: true
  100191. });
  100192. Layer.prototype._createIndexBuffer = function () {
  100193. var engine = this._scene.getEngine();
  100194. // Indices
  100195. var indices = [];
  100196. indices.push(0);
  100197. indices.push(1);
  100198. indices.push(2);
  100199. indices.push(0);
  100200. indices.push(2);
  100201. indices.push(3);
  100202. this._indexBuffer = engine.createIndexBuffer(indices);
  100203. };
  100204. Layer.prototype._rebuild = function () {
  100205. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100206. if (vb) {
  100207. vb._rebuild();
  100208. }
  100209. this._createIndexBuffer();
  100210. };
  100211. Layer.prototype.render = function () {
  100212. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  100213. // Check
  100214. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  100215. return;
  100216. var engine = this._scene.getEngine();
  100217. this.onBeforeRenderObservable.notifyObservers(this);
  100218. // Render
  100219. engine.enableEffect(currentEffect);
  100220. engine.setState(false);
  100221. // Texture
  100222. currentEffect.setTexture("textureSampler", this.texture);
  100223. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  100224. // Color
  100225. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  100226. // Scale / offset
  100227. currentEffect.setVector2("offset", this.offset);
  100228. currentEffect.setVector2("scale", this.scale);
  100229. // VBOs
  100230. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  100231. // Draw order
  100232. if (!this.alphaTest) {
  100233. engine.setAlphaMode(this.alphaBlendingMode);
  100234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100235. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  100236. }
  100237. else {
  100238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100239. }
  100240. this.onAfterRenderObservable.notifyObservers(this);
  100241. };
  100242. Layer.prototype.dispose = function () {
  100243. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  100244. if (vertexBuffer) {
  100245. vertexBuffer.dispose();
  100246. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  100247. }
  100248. if (this._indexBuffer) {
  100249. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  100250. this._indexBuffer = null;
  100251. }
  100252. if (this.texture) {
  100253. this.texture.dispose();
  100254. this.texture = null;
  100255. }
  100256. // Remove from scene
  100257. var index = this._scene.layers.indexOf(this);
  100258. this._scene.layers.splice(index, 1);
  100259. // Callback
  100260. this.onDisposeObservable.notifyObservers(this);
  100261. this.onDisposeObservable.clear();
  100262. this.onAfterRenderObservable.clear();
  100263. this.onBeforeRenderObservable.clear();
  100264. };
  100265. return Layer;
  100266. }());
  100267. BABYLON.Layer = Layer;
  100268. })(BABYLON || (BABYLON = {}));
  100269. //# sourceMappingURL=babylon.layer.js.map
  100270. var BABYLON;
  100271. (function (BABYLON) {
  100272. var TextureTools = /** @class */ (function () {
  100273. function TextureTools() {
  100274. }
  100275. /**
  100276. * Uses the GPU to create a copy texture rescaled at a given size
  100277. * @param texture Texture to copy from
  100278. * @param width Desired width
  100279. * @param height Desired height
  100280. * @return Generated texture
  100281. */
  100282. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  100283. if (useBilinearMode === void 0) { useBilinearMode = true; }
  100284. var scene = texture.getScene();
  100285. var engine = scene.getEngine();
  100286. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  100287. rtt.wrapU = texture.wrapU;
  100288. rtt.wrapV = texture.wrapV;
  100289. rtt.uOffset = texture.uOffset;
  100290. rtt.vOffset = texture.vOffset;
  100291. rtt.uScale = texture.uScale;
  100292. rtt.vScale = texture.vScale;
  100293. rtt.uAng = texture.uAng;
  100294. rtt.vAng = texture.vAng;
  100295. rtt.wAng = texture.wAng;
  100296. rtt.coordinatesIndex = texture.coordinatesIndex;
  100297. rtt.level = texture.level;
  100298. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  100299. rtt._texture.isReady = false;
  100300. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100301. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100302. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  100303. passPostProcess.getEffect().executeWhenCompiled(function () {
  100304. passPostProcess.onApply = function (effect) {
  100305. effect.setTexture("textureSampler", texture);
  100306. };
  100307. var internalTexture = rtt.getInternalTexture();
  100308. if (internalTexture) {
  100309. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  100310. engine.unBindFramebuffer(internalTexture);
  100311. rtt.disposeFramebufferObjects();
  100312. passPostProcess.dispose();
  100313. internalTexture.isReady = true;
  100314. }
  100315. });
  100316. return rtt;
  100317. };
  100318. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  100319. if (!scene._environmentBRDFTexture) {
  100320. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100321. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100322. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100323. scene._environmentBRDFTexture = texture;
  100324. }
  100325. return scene._environmentBRDFTexture;
  100326. };
  100327. 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=";
  100328. return TextureTools;
  100329. }());
  100330. BABYLON.TextureTools = TextureTools;
  100331. })(BABYLON || (BABYLON = {}));
  100332. //# sourceMappingURL=babylon.textureTools.js.map
  100333. var BABYLON;
  100334. (function (BABYLON) {
  100335. var FramingBehavior = /** @class */ (function () {
  100336. function FramingBehavior() {
  100337. this._mode = FramingBehavior.FitFrustumSidesMode;
  100338. this._radiusScale = 1.0;
  100339. this._positionScale = 0.5;
  100340. this._defaultElevation = 0.3;
  100341. this._elevationReturnTime = 1500;
  100342. this._elevationReturnWaitTime = 1000;
  100343. this._zoomStopsAnimation = false;
  100344. this._framingTime = 1500;
  100345. this._isPointerDown = false;
  100346. this._lastInteractionTime = -Infinity;
  100347. // Framing control
  100348. this._animatables = new Array();
  100349. this._betaIsAnimating = false;
  100350. }
  100351. Object.defineProperty(FramingBehavior.prototype, "name", {
  100352. get: function () {
  100353. return "Framing";
  100354. },
  100355. enumerable: true,
  100356. configurable: true
  100357. });
  100358. Object.defineProperty(FramingBehavior.prototype, "mode", {
  100359. /**
  100360. * Gets current mode used by the behavior.
  100361. */
  100362. get: function () {
  100363. return this._mode;
  100364. },
  100365. /**
  100366. * Sets the current mode used by the behavior
  100367. */
  100368. set: function (mode) {
  100369. this._mode = mode;
  100370. },
  100371. enumerable: true,
  100372. configurable: true
  100373. });
  100374. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  100375. /**
  100376. * Gets the scale applied to the radius
  100377. */
  100378. get: function () {
  100379. return this._radiusScale;
  100380. },
  100381. /**
  100382. * Sets the scale applied to the radius (1 by default)
  100383. */
  100384. set: function (radius) {
  100385. this._radiusScale = radius;
  100386. },
  100387. enumerable: true,
  100388. configurable: true
  100389. });
  100390. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  100391. /**
  100392. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100393. */
  100394. get: function () {
  100395. return this._positionScale;
  100396. },
  100397. /**
  100398. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  100399. */
  100400. set: function (scale) {
  100401. this._positionScale = scale;
  100402. },
  100403. enumerable: true,
  100404. configurable: true
  100405. });
  100406. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  100407. /**
  100408. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100409. * behaviour is triggered, in radians.
  100410. */
  100411. get: function () {
  100412. return this._defaultElevation;
  100413. },
  100414. /**
  100415. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  100416. * behaviour is triggered, in radians.
  100417. */
  100418. set: function (elevation) {
  100419. this._defaultElevation = elevation;
  100420. },
  100421. enumerable: true,
  100422. configurable: true
  100423. });
  100424. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  100425. /**
  100426. * Gets the time (in milliseconds) taken to return to the default beta position.
  100427. * Negative value indicates camera should not return to default.
  100428. */
  100429. get: function () {
  100430. return this._elevationReturnTime;
  100431. },
  100432. /**
  100433. * Sets the time (in milliseconds) taken to return to the default beta position.
  100434. * Negative value indicates camera should not return to default.
  100435. */
  100436. set: function (speed) {
  100437. this._elevationReturnTime = speed;
  100438. },
  100439. enumerable: true,
  100440. configurable: true
  100441. });
  100442. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  100443. /**
  100444. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100445. */
  100446. get: function () {
  100447. return this._elevationReturnWaitTime;
  100448. },
  100449. /**
  100450. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  100451. */
  100452. set: function (time) {
  100453. this._elevationReturnWaitTime = time;
  100454. },
  100455. enumerable: true,
  100456. configurable: true
  100457. });
  100458. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  100459. /**
  100460. * Gets the flag that indicates if user zooming should stop animation.
  100461. */
  100462. get: function () {
  100463. return this._zoomStopsAnimation;
  100464. },
  100465. /**
  100466. * Sets the flag that indicates if user zooming should stop animation.
  100467. */
  100468. set: function (flag) {
  100469. this._zoomStopsAnimation = flag;
  100470. },
  100471. enumerable: true,
  100472. configurable: true
  100473. });
  100474. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  100475. /**
  100476. * Gets the transition time when framing the mesh, in milliseconds
  100477. */
  100478. get: function () {
  100479. return this._framingTime;
  100480. },
  100481. /**
  100482. * Sets the transition time when framing the mesh, in milliseconds
  100483. */
  100484. set: function (time) {
  100485. this._framingTime = time;
  100486. },
  100487. enumerable: true,
  100488. configurable: true
  100489. });
  100490. FramingBehavior.prototype.init = function () {
  100491. // Do notihng
  100492. };
  100493. FramingBehavior.prototype.attach = function (camera) {
  100494. var _this = this;
  100495. this._attachedCamera = camera;
  100496. var scene = this._attachedCamera.getScene();
  100497. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  100498. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100499. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100500. _this._isPointerDown = true;
  100501. return;
  100502. }
  100503. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100504. _this._isPointerDown = false;
  100505. }
  100506. });
  100507. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100508. if (mesh) {
  100509. _this.zoomOnMesh(mesh);
  100510. }
  100511. });
  100512. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100513. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100514. _this._applyUserInteraction();
  100515. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  100516. // back to the default position after a given timeout
  100517. _this._maintainCameraAboveGround();
  100518. });
  100519. };
  100520. FramingBehavior.prototype.detach = function () {
  100521. if (!this._attachedCamera) {
  100522. return;
  100523. }
  100524. var scene = this._attachedCamera.getScene();
  100525. if (this._onPrePointerObservableObserver) {
  100526. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100527. }
  100528. if (this._onAfterCheckInputsObserver) {
  100529. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100530. }
  100531. if (this._onMeshTargetChangedObserver) {
  100532. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100533. }
  100534. this._attachedCamera = null;
  100535. };
  100536. /**
  100537. * Targets the given mesh and updates zoom level accordingly.
  100538. * @param mesh The mesh to target.
  100539. * @param radius Optional. If a cached radius position already exists, overrides default.
  100540. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100541. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100542. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100543. */
  100544. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100545. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100546. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100547. mesh.computeWorldMatrix(true);
  100548. var boundingBox = mesh.getBoundingInfo().boundingBox;
  100549. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  100550. };
  100551. /**
  100552. * Targets the given mesh with its children and updates zoom level accordingly.
  100553. * @param mesh The mesh to target.
  100554. * @param radius Optional. If a cached radius position already exists, overrides default.
  100555. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100556. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100557. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100558. */
  100559. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  100560. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100561. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100562. mesh.computeWorldMatrix(true);
  100563. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  100564. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  100565. };
  100566. /**
  100567. * Targets the given meshes with their children and updates zoom level accordingly.
  100568. * @param meshes The mesh to target.
  100569. * @param radius Optional. If a cached radius position already exists, overrides default.
  100570. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100571. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100572. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100573. */
  100574. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  100575. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100576. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100577. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  100578. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  100579. for (var i = 0; i < meshes.length; i++) {
  100580. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  100581. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  100582. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  100583. }
  100584. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  100585. };
  100586. /**
  100587. * Targets the given mesh and updates zoom level accordingly.
  100588. * @param mesh The mesh to target.
  100589. * @param radius Optional. If a cached radius position already exists, overrides default.
  100590. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  100591. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  100592. * @param onAnimationEnd Callback triggered at the end of the framing animation
  100593. */
  100594. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  100595. var _this = this;
  100596. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  100597. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  100598. var zoomTarget;
  100599. if (!this._attachedCamera) {
  100600. return;
  100601. }
  100602. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  100603. var bottom = minimumWorld.y;
  100604. var top = maximumWorld.y;
  100605. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  100606. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  100607. if (focusOnOriginXZ) {
  100608. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  100609. }
  100610. else {
  100611. var centerWorld = minimumWorld.add(radiusWorld);
  100612. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  100613. }
  100614. if (!this._vectorTransition) {
  100615. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  100616. }
  100617. this._betaIsAnimating = true;
  100618. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  100619. if (animatable) {
  100620. this._animatables.push(animatable);
  100621. }
  100622. // sets the radius and lower radius bounds
  100623. // Small delta ensures camera is not always at lower zoom limit.
  100624. var radius = 0;
  100625. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  100626. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100627. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  100628. radius = position;
  100629. }
  100630. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100631. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  100632. if (this._attachedCamera.lowerRadiusLimit === null) {
  100633. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  100634. }
  100635. }
  100636. // Set sensibilities
  100637. var extend = maximumWorld.subtract(minimumWorld).length();
  100638. this._attachedCamera.panningSensibility = 5000 / extend;
  100639. this._attachedCamera.wheelPrecision = 100 / radius;
  100640. // transition to new radius
  100641. if (!this._radiusTransition) {
  100642. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100643. }
  100644. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  100645. _this.stopAllAnimations();
  100646. if (onAnimationEnd) {
  100647. onAnimationEnd();
  100648. }
  100649. if (_this._attachedCamera) {
  100650. _this._attachedCamera.storeState();
  100651. }
  100652. });
  100653. if (animatable) {
  100654. this._animatables.push(animatable);
  100655. }
  100656. };
  100657. /**
  100658. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  100659. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  100660. * frustum width.
  100661. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  100662. * to fully enclose the mesh in the viewing frustum.
  100663. */
  100664. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  100665. var size = maximumWorld.subtract(minimumWorld);
  100666. var boxVectorGlobalDiagonal = size.length();
  100667. var frustumSlope = this._getFrustumSlope();
  100668. // Formula for setting distance
  100669. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  100670. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  100671. // Horizon distance
  100672. var radius = radiusWithoutFraming * this._radiusScale;
  100673. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  100674. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  100675. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  100676. var camera = this._attachedCamera;
  100677. if (!camera) {
  100678. return 0;
  100679. }
  100680. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  100681. // Don't exceed the requested limit
  100682. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  100683. }
  100684. // Don't exceed the upper radius limit
  100685. if (camera.upperRadiusLimit) {
  100686. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  100687. }
  100688. return distance;
  100689. };
  100690. /**
  100691. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  100692. * is automatically returned to its default position (expected to be above ground plane).
  100693. */
  100694. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  100695. var _this = this;
  100696. if (this._elevationReturnTime < 0) {
  100697. return;
  100698. }
  100699. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  100700. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  100701. var limitBeta = Math.PI * 0.5;
  100702. // Bring the camera back up if below the ground plane
  100703. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  100704. this._betaIsAnimating = true;
  100705. //Transition to new position
  100706. this.stopAllAnimations();
  100707. if (!this._betaTransition) {
  100708. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  100709. }
  100710. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  100711. _this._clearAnimationLocks();
  100712. _this.stopAllAnimations();
  100713. });
  100714. if (animatabe) {
  100715. this._animatables.push(animatabe);
  100716. }
  100717. }
  100718. };
  100719. /**
  100720. * Returns the frustum slope based on the canvas ratio and camera FOV
  100721. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  100722. */
  100723. FramingBehavior.prototype._getFrustumSlope = function () {
  100724. // Calculate the viewport ratio
  100725. // Aspect Ratio is Height/Width.
  100726. var camera = this._attachedCamera;
  100727. if (!camera) {
  100728. return BABYLON.Vector2.Zero();
  100729. }
  100730. var engine = camera.getScene().getEngine();
  100731. var aspectRatio = engine.getAspectRatio(camera);
  100732. // Camera FOV is the vertical field of view (top-bottom) in radians.
  100733. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  100734. var frustumSlopeY = Math.tan(camera.fov / 2);
  100735. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  100736. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  100737. // along the forward vector.
  100738. var frustumSlopeX = frustumSlopeY * aspectRatio;
  100739. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  100740. };
  100741. /**
  100742. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  100743. */
  100744. FramingBehavior.prototype._clearAnimationLocks = function () {
  100745. this._betaIsAnimating = false;
  100746. };
  100747. /**
  100748. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100749. */
  100750. FramingBehavior.prototype._applyUserInteraction = function () {
  100751. if (this.isUserIsMoving) {
  100752. this._lastInteractionTime = BABYLON.Tools.Now;
  100753. this.stopAllAnimations();
  100754. this._clearAnimationLocks();
  100755. }
  100756. };
  100757. /**
  100758. * Stops and removes all animations that have been applied to the camera
  100759. */
  100760. FramingBehavior.prototype.stopAllAnimations = function () {
  100761. if (this._attachedCamera) {
  100762. this._attachedCamera.animations = [];
  100763. }
  100764. while (this._animatables.length) {
  100765. if (this._animatables[0]) {
  100766. this._animatables[0].onAnimationEnd = null;
  100767. this._animatables[0].stop();
  100768. }
  100769. this._animatables.shift();
  100770. }
  100771. };
  100772. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  100773. /**
  100774. * Gets a value indicating if the user is moving the camera
  100775. */
  100776. get: function () {
  100777. if (!this._attachedCamera) {
  100778. return false;
  100779. }
  100780. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100781. this._attachedCamera.inertialBetaOffset !== 0 ||
  100782. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100783. this._attachedCamera.inertialPanningX !== 0 ||
  100784. this._attachedCamera.inertialPanningY !== 0 ||
  100785. this._isPointerDown;
  100786. },
  100787. enumerable: true,
  100788. configurable: true
  100789. });
  100790. /**
  100791. * The easing function used by animations
  100792. */
  100793. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  100794. /**
  100795. * The easing mode used by animations
  100796. */
  100797. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  100798. // Statics
  100799. /**
  100800. * The camera can move all the way towards the mesh.
  100801. */
  100802. FramingBehavior.IgnoreBoundsSizeMode = 0;
  100803. /**
  100804. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  100805. */
  100806. FramingBehavior.FitFrustumSidesMode = 1;
  100807. return FramingBehavior;
  100808. }());
  100809. BABYLON.FramingBehavior = FramingBehavior;
  100810. })(BABYLON || (BABYLON = {}));
  100811. //# sourceMappingURL=babylon.framingBehavior.js.map
  100812. var BABYLON;
  100813. (function (BABYLON) {
  100814. /**
  100815. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  100816. */
  100817. var BouncingBehavior = /** @class */ (function () {
  100818. function BouncingBehavior() {
  100819. /**
  100820. * The duration of the animation, in milliseconds
  100821. */
  100822. this.transitionDuration = 450;
  100823. /**
  100824. * Length of the distance animated by the transition when lower radius is reached
  100825. */
  100826. this.lowerRadiusTransitionRange = 2;
  100827. /**
  100828. * Length of the distance animated by the transition when upper radius is reached
  100829. */
  100830. this.upperRadiusTransitionRange = -2;
  100831. this._autoTransitionRange = false;
  100832. // Animations
  100833. this._radiusIsAnimating = false;
  100834. this._radiusBounceTransition = null;
  100835. this._animatables = new Array();
  100836. }
  100837. Object.defineProperty(BouncingBehavior.prototype, "name", {
  100838. get: function () {
  100839. return "Bouncing";
  100840. },
  100841. enumerable: true,
  100842. configurable: true
  100843. });
  100844. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  100845. /**
  100846. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100847. */
  100848. get: function () {
  100849. return this._autoTransitionRange;
  100850. },
  100851. /**
  100852. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  100853. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  100854. */
  100855. set: function (value) {
  100856. var _this = this;
  100857. if (this._autoTransitionRange === value) {
  100858. return;
  100859. }
  100860. this._autoTransitionRange = value;
  100861. var camera = this._attachedCamera;
  100862. if (!camera) {
  100863. return;
  100864. }
  100865. if (value) {
  100866. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  100867. if (!mesh) {
  100868. return;
  100869. }
  100870. mesh.computeWorldMatrix(true);
  100871. var diagonal = mesh.getBoundingInfo().diagonalLength;
  100872. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  100873. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100874. });
  100875. }
  100876. else if (this._onMeshTargetChangedObserver) {
  100877. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100878. }
  100879. },
  100880. enumerable: true,
  100881. configurable: true
  100882. });
  100883. BouncingBehavior.prototype.init = function () {
  100884. // Do notihng
  100885. };
  100886. BouncingBehavior.prototype.attach = function (camera) {
  100887. var _this = this;
  100888. this._attachedCamera = camera;
  100889. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100890. if (!_this._attachedCamera) {
  100891. return;
  100892. }
  100893. // Add the bounce animation to the lower radius limit
  100894. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100895. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100896. }
  100897. // Add the bounce animation to the upper radius limit
  100898. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100899. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100900. }
  100901. });
  100902. };
  100903. BouncingBehavior.prototype.detach = function () {
  100904. if (!this._attachedCamera) {
  100905. return;
  100906. }
  100907. if (this._onAfterCheckInputsObserver) {
  100908. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100909. }
  100910. if (this._onMeshTargetChangedObserver) {
  100911. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100912. }
  100913. this._attachedCamera = null;
  100914. };
  100915. /**
  100916. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100917. * @param radiusLimit The limit to check against.
  100918. * @return Bool to indicate if at limit.
  100919. */
  100920. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100921. if (!this._attachedCamera) {
  100922. return false;
  100923. }
  100924. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100925. return true;
  100926. }
  100927. return false;
  100928. };
  100929. /**
  100930. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100931. * @param radiusDelta The delta by which to animate to. Can be negative.
  100932. */
  100933. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100934. var _this = this;
  100935. if (!this._attachedCamera) {
  100936. return;
  100937. }
  100938. if (!this._radiusBounceTransition) {
  100939. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100940. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100941. }
  100942. // Prevent zoom until bounce has completed
  100943. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100944. this._attachedCamera.wheelPrecision = Infinity;
  100945. this._attachedCamera.inertialRadiusOffset = 0;
  100946. // Animate to the radius limit
  100947. this.stopAllAnimations();
  100948. this._radiusIsAnimating = true;
  100949. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100950. if (animatable) {
  100951. this._animatables.push(animatable);
  100952. }
  100953. };
  100954. /**
  100955. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100956. */
  100957. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100958. this._radiusIsAnimating = false;
  100959. if (this._attachedCamera) {
  100960. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100961. }
  100962. };
  100963. /**
  100964. * Stops and removes all animations that have been applied to the camera
  100965. */
  100966. BouncingBehavior.prototype.stopAllAnimations = function () {
  100967. if (this._attachedCamera) {
  100968. this._attachedCamera.animations = [];
  100969. }
  100970. while (this._animatables.length) {
  100971. this._animatables[0].onAnimationEnd = null;
  100972. this._animatables[0].stop();
  100973. this._animatables.shift();
  100974. }
  100975. };
  100976. /**
  100977. * The easing function used by animations
  100978. */
  100979. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100980. /**
  100981. * The easing mode used by animations
  100982. */
  100983. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100984. return BouncingBehavior;
  100985. }());
  100986. BABYLON.BouncingBehavior = BouncingBehavior;
  100987. })(BABYLON || (BABYLON = {}));
  100988. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100989. var BABYLON;
  100990. (function (BABYLON) {
  100991. var AutoRotationBehavior = /** @class */ (function () {
  100992. function AutoRotationBehavior() {
  100993. this._zoomStopsAnimation = false;
  100994. this._idleRotationSpeed = 0.05;
  100995. this._idleRotationWaitTime = 2000;
  100996. this._idleRotationSpinupTime = 2000;
  100997. this._isPointerDown = false;
  100998. this._lastFrameTime = null;
  100999. this._lastInteractionTime = -Infinity;
  101000. this._cameraRotationSpeed = 0;
  101001. this._lastFrameRadius = 0;
  101002. }
  101003. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  101004. get: function () {
  101005. return "AutoRotation";
  101006. },
  101007. enumerable: true,
  101008. configurable: true
  101009. });
  101010. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  101011. /**
  101012. * Gets the flag that indicates if user zooming should stop animation.
  101013. */
  101014. get: function () {
  101015. return this._zoomStopsAnimation;
  101016. },
  101017. /**
  101018. * Sets the flag that indicates if user zooming should stop animation.
  101019. */
  101020. set: function (flag) {
  101021. this._zoomStopsAnimation = flag;
  101022. },
  101023. enumerable: true,
  101024. configurable: true
  101025. });
  101026. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  101027. /**
  101028. * Gets the default speed at which the camera rotates around the model.
  101029. */
  101030. get: function () {
  101031. return this._idleRotationSpeed;
  101032. },
  101033. /**
  101034. * Sets the default speed at which the camera rotates around the model.
  101035. */
  101036. set: function (speed) {
  101037. this._idleRotationSpeed = speed;
  101038. },
  101039. enumerable: true,
  101040. configurable: true
  101041. });
  101042. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  101043. /**
  101044. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  101045. */
  101046. get: function () {
  101047. return this._idleRotationWaitTime;
  101048. },
  101049. /**
  101050. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  101051. */
  101052. set: function (time) {
  101053. this._idleRotationWaitTime = time;
  101054. },
  101055. enumerable: true,
  101056. configurable: true
  101057. });
  101058. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  101059. /**
  101060. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101061. */
  101062. get: function () {
  101063. return this._idleRotationSpinupTime;
  101064. },
  101065. /**
  101066. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  101067. */
  101068. set: function (time) {
  101069. this._idleRotationSpinupTime = time;
  101070. },
  101071. enumerable: true,
  101072. configurable: true
  101073. });
  101074. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  101075. /**
  101076. * Gets a value indicating if the camera is currently rotating because of this behavior
  101077. */
  101078. get: function () {
  101079. return Math.abs(this._cameraRotationSpeed) > 0;
  101080. },
  101081. enumerable: true,
  101082. configurable: true
  101083. });
  101084. AutoRotationBehavior.prototype.init = function () {
  101085. // Do notihng
  101086. };
  101087. AutoRotationBehavior.prototype.attach = function (camera) {
  101088. var _this = this;
  101089. this._attachedCamera = camera;
  101090. var scene = this._attachedCamera.getScene();
  101091. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  101092. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  101093. _this._isPointerDown = true;
  101094. return;
  101095. }
  101096. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  101097. _this._isPointerDown = false;
  101098. }
  101099. });
  101100. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  101101. var now = BABYLON.Tools.Now;
  101102. var dt = 0;
  101103. if (_this._lastFrameTime != null) {
  101104. dt = now - _this._lastFrameTime;
  101105. }
  101106. _this._lastFrameTime = now;
  101107. // Stop the animation if there is user interaction and the animation should stop for this interaction
  101108. _this._applyUserInteraction();
  101109. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  101110. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  101111. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  101112. // Step camera rotation by rotation speed
  101113. if (_this._attachedCamera) {
  101114. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  101115. }
  101116. });
  101117. };
  101118. AutoRotationBehavior.prototype.detach = function () {
  101119. if (!this._attachedCamera) {
  101120. return;
  101121. }
  101122. var scene = this._attachedCamera.getScene();
  101123. if (this._onPrePointerObservableObserver) {
  101124. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  101125. }
  101126. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  101127. this._attachedCamera = null;
  101128. };
  101129. /**
  101130. * Returns true if user is scrolling.
  101131. * @return true if user is scrolling.
  101132. */
  101133. AutoRotationBehavior.prototype._userIsZooming = function () {
  101134. if (!this._attachedCamera) {
  101135. return false;
  101136. }
  101137. return this._attachedCamera.inertialRadiusOffset !== 0;
  101138. };
  101139. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  101140. if (!this._attachedCamera) {
  101141. return false;
  101142. }
  101143. var zoomHasHitLimit = false;
  101144. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  101145. zoomHasHitLimit = true;
  101146. }
  101147. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  101148. this._lastFrameRadius = this._attachedCamera.radius;
  101149. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  101150. };
  101151. /**
  101152. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  101153. */
  101154. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  101155. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  101156. this._lastInteractionTime = BABYLON.Tools.Now;
  101157. }
  101158. };
  101159. // Tools
  101160. AutoRotationBehavior.prototype._userIsMoving = function () {
  101161. if (!this._attachedCamera) {
  101162. return false;
  101163. }
  101164. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  101165. this._attachedCamera.inertialBetaOffset !== 0 ||
  101166. this._attachedCamera.inertialRadiusOffset !== 0 ||
  101167. this._attachedCamera.inertialPanningX !== 0 ||
  101168. this._attachedCamera.inertialPanningY !== 0 ||
  101169. this._isPointerDown;
  101170. };
  101171. return AutoRotationBehavior;
  101172. }());
  101173. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  101174. })(BABYLON || (BABYLON = {}));
  101175. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  101176. var BABYLON;
  101177. (function (BABYLON) {
  101178. var NullEngineOptions = /** @class */ (function () {
  101179. function NullEngineOptions() {
  101180. this.renderWidth = 512;
  101181. this.renderHeight = 256;
  101182. this.textureSize = 512;
  101183. this.deterministicLockstep = false;
  101184. this.lockstepMaxSteps = 4;
  101185. }
  101186. return NullEngineOptions;
  101187. }());
  101188. BABYLON.NullEngineOptions = NullEngineOptions;
  101189. /**
  101190. * The null engine class provides support for headless version of babylon.js.
  101191. * This can be used in server side scenario or for testing purposes
  101192. */
  101193. var NullEngine = /** @class */ (function (_super) {
  101194. __extends(NullEngine, _super);
  101195. function NullEngine(options) {
  101196. if (options === void 0) { options = new NullEngineOptions(); }
  101197. var _this = _super.call(this, null) || this;
  101198. if (options.deterministicLockstep === undefined) {
  101199. options.deterministicLockstep = false;
  101200. }
  101201. if (options.lockstepMaxSteps === undefined) {
  101202. options.lockstepMaxSteps = 4;
  101203. }
  101204. _this._options = options;
  101205. // Init caps
  101206. // We consider we are on a webgl1 capable device
  101207. _this._caps = new BABYLON.EngineCapabilities();
  101208. _this._caps.maxTexturesImageUnits = 16;
  101209. _this._caps.maxVertexTextureImageUnits = 16;
  101210. _this._caps.maxTextureSize = 512;
  101211. _this._caps.maxCubemapTextureSize = 512;
  101212. _this._caps.maxRenderTextureSize = 512;
  101213. _this._caps.maxVertexAttribs = 16;
  101214. _this._caps.maxVaryingVectors = 16;
  101215. _this._caps.maxFragmentUniformVectors = 16;
  101216. _this._caps.maxVertexUniformVectors = 16;
  101217. // Extensions
  101218. _this._caps.standardDerivatives = false;
  101219. _this._caps.astc = null;
  101220. _this._caps.s3tc = null;
  101221. _this._caps.pvrtc = null;
  101222. _this._caps.etc1 = null;
  101223. _this._caps.etc2 = null;
  101224. _this._caps.textureAnisotropicFilterExtension = null;
  101225. _this._caps.maxAnisotropy = 0;
  101226. _this._caps.uintIndices = false;
  101227. _this._caps.fragmentDepthSupported = false;
  101228. _this._caps.highPrecisionShaderSupported = true;
  101229. _this._caps.colorBufferFloat = false;
  101230. _this._caps.textureFloat = false;
  101231. _this._caps.textureFloatLinearFiltering = false;
  101232. _this._caps.textureFloatRender = false;
  101233. _this._caps.textureHalfFloat = false;
  101234. _this._caps.textureHalfFloatLinearFiltering = false;
  101235. _this._caps.textureHalfFloatRender = false;
  101236. _this._caps.textureLOD = false;
  101237. _this._caps.drawBuffersExtension = false;
  101238. _this._caps.depthTextureExtension = false;
  101239. _this._caps.vertexArrayObject = false;
  101240. _this._caps.instancedArrays = false;
  101241. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  101242. // Wrappers
  101243. if (typeof URL === "undefined") {
  101244. URL = {
  101245. createObjectURL: function () { },
  101246. revokeObjectURL: function () { }
  101247. };
  101248. }
  101249. if (typeof Blob === "undefined") {
  101250. Blob = function () { };
  101251. }
  101252. return _this;
  101253. }
  101254. NullEngine.prototype.isDeterministicLockStep = function () {
  101255. return this._options.deterministicLockstep;
  101256. };
  101257. NullEngine.prototype.getLockstepMaxSteps = function () {
  101258. return this._options.lockstepMaxSteps;
  101259. };
  101260. NullEngine.prototype.getHardwareScalingLevel = function () {
  101261. return 1.0;
  101262. };
  101263. NullEngine.prototype.createVertexBuffer = function (vertices) {
  101264. return {
  101265. capacity: 0,
  101266. references: 1,
  101267. is32Bits: false
  101268. };
  101269. };
  101270. NullEngine.prototype.createIndexBuffer = function (indices) {
  101271. return {
  101272. capacity: 0,
  101273. references: 1,
  101274. is32Bits: false
  101275. };
  101276. };
  101277. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  101278. if (stencil === void 0) { stencil = false; }
  101279. };
  101280. NullEngine.prototype.getRenderWidth = function (useScreen) {
  101281. if (useScreen === void 0) { useScreen = false; }
  101282. if (!useScreen && this._currentRenderTarget) {
  101283. return this._currentRenderTarget.width;
  101284. }
  101285. return this._options.renderWidth;
  101286. };
  101287. NullEngine.prototype.getRenderHeight = function (useScreen) {
  101288. if (useScreen === void 0) { useScreen = false; }
  101289. if (!useScreen && this._currentRenderTarget) {
  101290. return this._currentRenderTarget.height;
  101291. }
  101292. return this._options.renderHeight;
  101293. };
  101294. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  101295. this._cachedViewport = viewport;
  101296. };
  101297. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  101298. return {
  101299. transformFeedback: null,
  101300. __SPECTOR_rebuildProgram: null
  101301. };
  101302. };
  101303. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  101304. return [];
  101305. };
  101306. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  101307. return [];
  101308. };
  101309. NullEngine.prototype.bindSamplers = function (effect) {
  101310. this._currentEffect = null;
  101311. };
  101312. NullEngine.prototype.enableEffect = function (effect) {
  101313. this._currentEffect = effect;
  101314. if (effect.onBind) {
  101315. effect.onBind(effect);
  101316. }
  101317. effect.onBindObservable.notifyObservers(effect);
  101318. };
  101319. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  101320. if (zOffset === void 0) { zOffset = 0; }
  101321. if (reverseSide === void 0) { reverseSide = false; }
  101322. };
  101323. NullEngine.prototype.setIntArray = function (uniform, array) {
  101324. };
  101325. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  101326. };
  101327. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  101328. };
  101329. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  101330. };
  101331. NullEngine.prototype.setFloatArray = function (uniform, array) {
  101332. };
  101333. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  101334. };
  101335. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  101336. };
  101337. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  101338. };
  101339. NullEngine.prototype.setArray = function (uniform, array) {
  101340. };
  101341. NullEngine.prototype.setArray2 = function (uniform, array) {
  101342. };
  101343. NullEngine.prototype.setArray3 = function (uniform, array) {
  101344. };
  101345. NullEngine.prototype.setArray4 = function (uniform, array) {
  101346. };
  101347. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  101348. };
  101349. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  101350. };
  101351. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  101352. };
  101353. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  101354. };
  101355. NullEngine.prototype.setFloat = function (uniform, value) {
  101356. };
  101357. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  101358. };
  101359. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  101360. };
  101361. NullEngine.prototype.setBool = function (uniform, bool) {
  101362. };
  101363. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  101364. };
  101365. NullEngine.prototype.setColor3 = function (uniform, color3) {
  101366. };
  101367. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  101368. };
  101369. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  101370. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  101371. if (this._alphaMode === mode) {
  101372. return;
  101373. }
  101374. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  101375. if (!noDepthWriteChange) {
  101376. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  101377. }
  101378. this._alphaMode = mode;
  101379. };
  101380. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  101381. };
  101382. NullEngine.prototype.wipeCaches = function (bruteForce) {
  101383. if (this.preventCacheWipeBetweenFrames) {
  101384. return;
  101385. }
  101386. this.resetTextureCache();
  101387. this._currentEffect = null;
  101388. if (bruteForce) {
  101389. this._currentProgram = null;
  101390. this._stencilState.reset();
  101391. this._depthCullingState.reset();
  101392. this._alphaState.reset();
  101393. }
  101394. this._cachedVertexBuffers = null;
  101395. this._cachedIndexBuffer = null;
  101396. this._cachedEffectForVertexBuffers = null;
  101397. };
  101398. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  101399. };
  101400. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  101401. };
  101402. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  101403. };
  101404. NullEngine.prototype._createTexture = function () {
  101405. return {};
  101406. };
  101407. NullEngine.prototype._releaseTexture = function (texture) {
  101408. };
  101409. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  101410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101411. if (onLoad === void 0) { onLoad = null; }
  101412. if (onError === void 0) { onError = null; }
  101413. if (buffer === void 0) { buffer = null; }
  101414. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  101415. var url = String(urlArg);
  101416. texture.url = url;
  101417. texture.generateMipMaps = !noMipmap;
  101418. texture.samplingMode = samplingMode;
  101419. texture.invertY = invertY;
  101420. texture.baseWidth = this._options.textureSize;
  101421. texture.baseHeight = this._options.textureSize;
  101422. texture.width = this._options.textureSize;
  101423. texture.height = this._options.textureSize;
  101424. if (format) {
  101425. texture.format = format;
  101426. }
  101427. texture.isReady = true;
  101428. if (onLoad) {
  101429. onLoad();
  101430. }
  101431. this._internalTexturesCache.push(texture);
  101432. return texture;
  101433. };
  101434. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  101435. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  101436. if (options !== undefined && typeof options === "object") {
  101437. fullOptions.generateMipMaps = options.generateMipMaps;
  101438. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  101439. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  101440. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  101441. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  101442. }
  101443. else {
  101444. fullOptions.generateMipMaps = options;
  101445. fullOptions.generateDepthBuffer = true;
  101446. fullOptions.generateStencilBuffer = false;
  101447. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  101448. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  101449. }
  101450. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  101451. var width = size.width || size;
  101452. var height = size.height || size;
  101453. texture._depthStencilBuffer = {};
  101454. texture._framebuffer = {};
  101455. texture.baseWidth = width;
  101456. texture.baseHeight = height;
  101457. texture.width = width;
  101458. texture.height = height;
  101459. texture.isReady = true;
  101460. texture.samples = 1;
  101461. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  101462. texture.samplingMode = fullOptions.samplingMode;
  101463. texture.type = fullOptions.type;
  101464. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  101465. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  101466. this._internalTexturesCache.push(texture);
  101467. return texture;
  101468. };
  101469. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  101470. texture.samplingMode = samplingMode;
  101471. };
  101472. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  101473. if (this._currentRenderTarget) {
  101474. this.unBindFramebuffer(this._currentRenderTarget);
  101475. }
  101476. this._currentRenderTarget = texture;
  101477. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  101478. if (this._cachedViewport && !forceFullscreenViewport) {
  101479. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  101480. }
  101481. };
  101482. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  101483. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  101484. this._currentRenderTarget = null;
  101485. if (onBeforeUnbind) {
  101486. if (texture._MSAAFramebuffer) {
  101487. this._currentFramebuffer = texture._framebuffer;
  101488. }
  101489. onBeforeUnbind();
  101490. }
  101491. this._currentFramebuffer = null;
  101492. };
  101493. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  101494. var vbo = {
  101495. capacity: 1,
  101496. references: 1,
  101497. is32Bits: false
  101498. };
  101499. return vbo;
  101500. };
  101501. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  101502. if (premulAlpha === void 0) { premulAlpha = false; }
  101503. };
  101504. /**
  101505. * Get the current error code of the webGL context
  101506. * @returns the error code
  101507. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  101508. */
  101509. NullEngine.prototype.getError = function () {
  101510. return 0;
  101511. };
  101512. /** @hidden */
  101513. NullEngine.prototype._getUnpackAlignement = function () {
  101514. return 1;
  101515. };
  101516. /** @hidden */
  101517. NullEngine.prototype._unpackFlipY = function (value) {
  101518. };
  101519. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  101520. if (offset === void 0) { offset = 0; }
  101521. };
  101522. /**
  101523. * Updates a dynamic vertex buffer.
  101524. * @param vertexBuffer the vertex buffer to update
  101525. * @param data the data used to update the vertex buffer
  101526. * @param byteOffset the byte offset of the data (optional)
  101527. * @param byteLength the byte length of the data (optional)
  101528. */
  101529. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  101530. };
  101531. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  101532. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  101533. this._boundTexturesCache[this._activeChannel] = texture;
  101534. return true;
  101535. }
  101536. return false;
  101537. };
  101538. NullEngine.prototype._bindTexture = function (channel, texture) {
  101539. if (channel < 0) {
  101540. return;
  101541. }
  101542. this._bindTextureDirectly(0, texture);
  101543. };
  101544. NullEngine.prototype._releaseBuffer = function (buffer) {
  101545. buffer.references--;
  101546. if (buffer.references === 0) {
  101547. return true;
  101548. }
  101549. return false;
  101550. };
  101551. NullEngine.prototype.releaseEffects = function () {
  101552. };
  101553. NullEngine.prototype.displayLoadingUI = function () {
  101554. };
  101555. NullEngine.prototype.hideLoadingUI = function () {
  101556. };
  101557. /** @hidden */
  101558. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  101559. if (faceIndex === void 0) { faceIndex = 0; }
  101560. if (lod === void 0) { lod = 0; }
  101561. };
  101562. /** @hidden */
  101563. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  101564. if (faceIndex === void 0) { faceIndex = 0; }
  101565. if (lod === void 0) { lod = 0; }
  101566. };
  101567. /** @hidden */
  101568. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  101569. if (faceIndex === void 0) { faceIndex = 0; }
  101570. if (lod === void 0) { lod = 0; }
  101571. };
  101572. /** @hidden */
  101573. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  101574. if (faceIndex === void 0) { faceIndex = 0; }
  101575. if (lod === void 0) { lod = 0; }
  101576. };
  101577. return NullEngine;
  101578. }(BABYLON.Engine));
  101579. BABYLON.NullEngine = NullEngine;
  101580. })(BABYLON || (BABYLON = {}));
  101581. //# sourceMappingURL=babylon.nullEngine.js.map
  101582. var BABYLON;
  101583. (function (BABYLON) {
  101584. /**
  101585. * This class can be used to get instrumentation data from a Babylon engine
  101586. */
  101587. var EngineInstrumentation = /** @class */ (function () {
  101588. function EngineInstrumentation(engine) {
  101589. this.engine = engine;
  101590. this._captureGPUFrameTime = false;
  101591. this._gpuFrameTime = new BABYLON.PerfCounter();
  101592. this._captureShaderCompilationTime = false;
  101593. this._shaderCompilationTime = new BABYLON.PerfCounter();
  101594. // Observers
  101595. this._onBeginFrameObserver = null;
  101596. this._onEndFrameObserver = null;
  101597. this._onBeforeShaderCompilationObserver = null;
  101598. this._onAfterShaderCompilationObserver = null;
  101599. }
  101600. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  101601. // Properties
  101602. /**
  101603. * Gets the perf counter used for GPU frame time
  101604. */
  101605. get: function () {
  101606. return this._gpuFrameTime;
  101607. },
  101608. enumerable: true,
  101609. configurable: true
  101610. });
  101611. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  101612. /**
  101613. * Gets the GPU frame time capture status
  101614. */
  101615. get: function () {
  101616. return this._captureGPUFrameTime;
  101617. },
  101618. /**
  101619. * Enable or disable the GPU frame time capture
  101620. */
  101621. set: function (value) {
  101622. var _this = this;
  101623. if (value === this._captureGPUFrameTime) {
  101624. return;
  101625. }
  101626. this._captureGPUFrameTime = value;
  101627. if (value) {
  101628. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  101629. if (!_this._gpuFrameTimeToken) {
  101630. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  101631. }
  101632. });
  101633. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  101634. if (!_this._gpuFrameTimeToken) {
  101635. return;
  101636. }
  101637. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  101638. if (time > -1) {
  101639. _this._gpuFrameTimeToken = null;
  101640. _this._gpuFrameTime.fetchNewFrame();
  101641. _this._gpuFrameTime.addCount(time, true);
  101642. }
  101643. });
  101644. }
  101645. else {
  101646. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101647. this._onBeginFrameObserver = null;
  101648. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101649. this._onEndFrameObserver = null;
  101650. }
  101651. },
  101652. enumerable: true,
  101653. configurable: true
  101654. });
  101655. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  101656. /**
  101657. * Gets the perf counter used for shader compilation time
  101658. */
  101659. get: function () {
  101660. return this._shaderCompilationTime;
  101661. },
  101662. enumerable: true,
  101663. configurable: true
  101664. });
  101665. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  101666. /**
  101667. * Gets the shader compilation time capture status
  101668. */
  101669. get: function () {
  101670. return this._captureShaderCompilationTime;
  101671. },
  101672. /**
  101673. * Enable or disable the shader compilation time capture
  101674. */
  101675. set: function (value) {
  101676. var _this = this;
  101677. if (value === this._captureShaderCompilationTime) {
  101678. return;
  101679. }
  101680. this._captureShaderCompilationTime = value;
  101681. if (value) {
  101682. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  101683. _this._shaderCompilationTime.fetchNewFrame();
  101684. _this._shaderCompilationTime.beginMonitoring();
  101685. });
  101686. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  101687. _this._shaderCompilationTime.endMonitoring();
  101688. });
  101689. }
  101690. else {
  101691. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101692. this._onBeforeShaderCompilationObserver = null;
  101693. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101694. this._onAfterShaderCompilationObserver = null;
  101695. }
  101696. },
  101697. enumerable: true,
  101698. configurable: true
  101699. });
  101700. EngineInstrumentation.prototype.dispose = function () {
  101701. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  101702. this._onBeginFrameObserver = null;
  101703. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  101704. this._onEndFrameObserver = null;
  101705. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  101706. this._onBeforeShaderCompilationObserver = null;
  101707. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  101708. this._onAfterShaderCompilationObserver = null;
  101709. this.engine = null;
  101710. };
  101711. return EngineInstrumentation;
  101712. }());
  101713. BABYLON.EngineInstrumentation = EngineInstrumentation;
  101714. })(BABYLON || (BABYLON = {}));
  101715. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  101716. var BABYLON;
  101717. (function (BABYLON) {
  101718. /**
  101719. * This class can be used to get instrumentation data from a Babylon engine
  101720. */
  101721. var SceneInstrumentation = /** @class */ (function () {
  101722. function SceneInstrumentation(scene) {
  101723. var _this = this;
  101724. this.scene = scene;
  101725. this._captureActiveMeshesEvaluationTime = false;
  101726. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  101727. this._captureRenderTargetsRenderTime = false;
  101728. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  101729. this._captureFrameTime = false;
  101730. this._frameTime = new BABYLON.PerfCounter();
  101731. this._captureRenderTime = false;
  101732. this._renderTime = new BABYLON.PerfCounter();
  101733. this._captureInterFrameTime = false;
  101734. this._interFrameTime = new BABYLON.PerfCounter();
  101735. this._captureParticlesRenderTime = false;
  101736. this._particlesRenderTime = new BABYLON.PerfCounter();
  101737. this._captureSpritesRenderTime = false;
  101738. this._spritesRenderTime = new BABYLON.PerfCounter();
  101739. this._capturePhysicsTime = false;
  101740. this._physicsTime = new BABYLON.PerfCounter();
  101741. this._captureAnimationsTime = false;
  101742. this._animationsTime = new BABYLON.PerfCounter();
  101743. this._captureCameraRenderTime = false;
  101744. this._cameraRenderTime = new BABYLON.PerfCounter();
  101745. // Observers
  101746. this._onBeforeActiveMeshesEvaluationObserver = null;
  101747. this._onAfterActiveMeshesEvaluationObserver = null;
  101748. this._onBeforeRenderTargetsRenderObserver = null;
  101749. this._onAfterRenderTargetsRenderObserver = null;
  101750. this._onAfterRenderObserver = null;
  101751. this._onBeforeDrawPhaseObserver = null;
  101752. this._onAfterDrawPhaseObserver = null;
  101753. this._onBeforeAnimationsObserver = null;
  101754. this._onBeforeParticlesRenderingObserver = null;
  101755. this._onAfterParticlesRenderingObserver = null;
  101756. this._onBeforeSpritesRenderingObserver = null;
  101757. this._onAfterSpritesRenderingObserver = null;
  101758. this._onBeforePhysicsObserver = null;
  101759. this._onAfterPhysicsObserver = null;
  101760. this._onAfterAnimationsObserver = null;
  101761. this._onBeforeCameraRenderObserver = null;
  101762. this._onAfterCameraRenderObserver = null;
  101763. // Before render
  101764. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  101765. if (_this._captureActiveMeshesEvaluationTime) {
  101766. _this._activeMeshesEvaluationTime.fetchNewFrame();
  101767. }
  101768. if (_this._captureRenderTargetsRenderTime) {
  101769. _this._renderTargetsRenderTime.fetchNewFrame();
  101770. }
  101771. if (_this._captureFrameTime) {
  101772. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  101773. _this._frameTime.beginMonitoring();
  101774. }
  101775. if (_this._captureInterFrameTime) {
  101776. _this._interFrameTime.endMonitoring();
  101777. }
  101778. if (_this._captureParticlesRenderTime) {
  101779. _this._particlesRenderTime.fetchNewFrame();
  101780. }
  101781. if (_this._captureSpritesRenderTime) {
  101782. _this._spritesRenderTime.fetchNewFrame();
  101783. }
  101784. if (_this._captureAnimationsTime) {
  101785. _this._animationsTime.beginMonitoring();
  101786. }
  101787. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  101788. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  101789. });
  101790. // After render
  101791. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  101792. if (_this._captureFrameTime) {
  101793. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  101794. _this._frameTime.endMonitoring();
  101795. }
  101796. if (_this._captureRenderTime) {
  101797. _this._renderTime.endMonitoring(false);
  101798. }
  101799. if (_this._captureInterFrameTime) {
  101800. _this._interFrameTime.beginMonitoring();
  101801. }
  101802. });
  101803. }
  101804. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  101805. // Properties
  101806. /**
  101807. * Gets the perf counter used for active meshes evaluation time
  101808. */
  101809. get: function () {
  101810. return this._activeMeshesEvaluationTime;
  101811. },
  101812. enumerable: true,
  101813. configurable: true
  101814. });
  101815. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  101816. /**
  101817. * Gets the active meshes evaluation time capture status
  101818. */
  101819. get: function () {
  101820. return this._captureActiveMeshesEvaluationTime;
  101821. },
  101822. /**
  101823. * Enable or disable the active meshes evaluation time capture
  101824. */
  101825. set: function (value) {
  101826. var _this = this;
  101827. if (value === this._captureActiveMeshesEvaluationTime) {
  101828. return;
  101829. }
  101830. this._captureActiveMeshesEvaluationTime = value;
  101831. if (value) {
  101832. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  101833. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  101834. _this._activeMeshesEvaluationTime.beginMonitoring();
  101835. });
  101836. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  101837. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  101838. _this._activeMeshesEvaluationTime.endMonitoring();
  101839. });
  101840. }
  101841. else {
  101842. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101843. this._onBeforeActiveMeshesEvaluationObserver = null;
  101844. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101845. this._onAfterActiveMeshesEvaluationObserver = null;
  101846. }
  101847. },
  101848. enumerable: true,
  101849. configurable: true
  101850. });
  101851. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  101852. /**
  101853. * Gets the perf counter used for render targets render time
  101854. */
  101855. get: function () {
  101856. return this._renderTargetsRenderTime;
  101857. },
  101858. enumerable: true,
  101859. configurable: true
  101860. });
  101861. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  101862. /**
  101863. * Gets the render targets render time capture status
  101864. */
  101865. get: function () {
  101866. return this._captureRenderTargetsRenderTime;
  101867. },
  101868. /**
  101869. * Enable or disable the render targets render time capture
  101870. */
  101871. set: function (value) {
  101872. var _this = this;
  101873. if (value === this._captureRenderTargetsRenderTime) {
  101874. return;
  101875. }
  101876. this._captureRenderTargetsRenderTime = value;
  101877. if (value) {
  101878. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  101879. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  101880. _this._renderTargetsRenderTime.beginMonitoring();
  101881. });
  101882. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  101883. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  101884. _this._renderTargetsRenderTime.endMonitoring(false);
  101885. });
  101886. }
  101887. else {
  101888. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101889. this._onBeforeRenderTargetsRenderObserver = null;
  101890. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101891. this._onAfterRenderTargetsRenderObserver = null;
  101892. }
  101893. },
  101894. enumerable: true,
  101895. configurable: true
  101896. });
  101897. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  101898. /**
  101899. * Gets the perf counter used for particles render time
  101900. */
  101901. get: function () {
  101902. return this._particlesRenderTime;
  101903. },
  101904. enumerable: true,
  101905. configurable: true
  101906. });
  101907. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  101908. /**
  101909. * Gets the particles render time capture status
  101910. */
  101911. get: function () {
  101912. return this._captureParticlesRenderTime;
  101913. },
  101914. /**
  101915. * Enable or disable the particles render time capture
  101916. */
  101917. set: function (value) {
  101918. var _this = this;
  101919. if (value === this._captureParticlesRenderTime) {
  101920. return;
  101921. }
  101922. this._captureParticlesRenderTime = value;
  101923. if (value) {
  101924. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101925. BABYLON.Tools.StartPerformanceCounter("Particles");
  101926. _this._particlesRenderTime.beginMonitoring();
  101927. });
  101928. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101929. BABYLON.Tools.EndPerformanceCounter("Particles");
  101930. _this._particlesRenderTime.endMonitoring(false);
  101931. });
  101932. }
  101933. else {
  101934. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101935. this._onBeforeParticlesRenderingObserver = null;
  101936. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101937. this._onAfterParticlesRenderingObserver = null;
  101938. }
  101939. },
  101940. enumerable: true,
  101941. configurable: true
  101942. });
  101943. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101944. /**
  101945. * Gets the perf counter used for sprites render time
  101946. */
  101947. get: function () {
  101948. return this._spritesRenderTime;
  101949. },
  101950. enumerable: true,
  101951. configurable: true
  101952. });
  101953. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101954. /**
  101955. * Gets the sprites render time capture status
  101956. */
  101957. get: function () {
  101958. return this._captureSpritesRenderTime;
  101959. },
  101960. /**
  101961. * Enable or disable the sprites render time capture
  101962. */
  101963. set: function (value) {
  101964. var _this = this;
  101965. if (value === this._captureSpritesRenderTime) {
  101966. return;
  101967. }
  101968. this._captureSpritesRenderTime = value;
  101969. if (value) {
  101970. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101971. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101972. _this._spritesRenderTime.beginMonitoring();
  101973. });
  101974. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101975. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101976. _this._spritesRenderTime.endMonitoring(false);
  101977. });
  101978. }
  101979. else {
  101980. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101981. this._onBeforeSpritesRenderingObserver = null;
  101982. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101983. this._onAfterSpritesRenderingObserver = null;
  101984. }
  101985. },
  101986. enumerable: true,
  101987. configurable: true
  101988. });
  101989. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101990. /**
  101991. * Gets the perf counter used for physics time
  101992. */
  101993. get: function () {
  101994. return this._physicsTime;
  101995. },
  101996. enumerable: true,
  101997. configurable: true
  101998. });
  101999. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  102000. /**
  102001. * Gets the physics time capture status
  102002. */
  102003. get: function () {
  102004. return this._capturePhysicsTime;
  102005. },
  102006. /**
  102007. * Enable or disable the physics time capture
  102008. */
  102009. set: function (value) {
  102010. var _this = this;
  102011. if (value === this._capturePhysicsTime) {
  102012. return;
  102013. }
  102014. this._capturePhysicsTime = value;
  102015. if (value) {
  102016. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  102017. BABYLON.Tools.StartPerformanceCounter("Physics");
  102018. _this._physicsTime.beginMonitoring();
  102019. });
  102020. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  102021. BABYLON.Tools.EndPerformanceCounter("Physics");
  102022. _this._physicsTime.endMonitoring();
  102023. });
  102024. }
  102025. else {
  102026. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102027. this._onBeforePhysicsObserver = null;
  102028. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102029. this._onAfterPhysicsObserver = null;
  102030. }
  102031. },
  102032. enumerable: true,
  102033. configurable: true
  102034. });
  102035. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  102036. /**
  102037. * Gets the perf counter used for animations time
  102038. */
  102039. get: function () {
  102040. return this._animationsTime;
  102041. },
  102042. enumerable: true,
  102043. configurable: true
  102044. });
  102045. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  102046. /**
  102047. * Gets the animations time capture status
  102048. */
  102049. get: function () {
  102050. return this._captureAnimationsTime;
  102051. },
  102052. /**
  102053. * Enable or disable the animations time capture
  102054. */
  102055. set: function (value) {
  102056. var _this = this;
  102057. if (value === this._captureAnimationsTime) {
  102058. return;
  102059. }
  102060. this._captureAnimationsTime = value;
  102061. if (value) {
  102062. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  102063. _this._animationsTime.endMonitoring();
  102064. });
  102065. }
  102066. else {
  102067. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102068. this._onAfterAnimationsObserver = null;
  102069. }
  102070. },
  102071. enumerable: true,
  102072. configurable: true
  102073. });
  102074. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  102075. /**
  102076. * Gets the perf counter used for frame time capture
  102077. */
  102078. get: function () {
  102079. return this._frameTime;
  102080. },
  102081. enumerable: true,
  102082. configurable: true
  102083. });
  102084. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  102085. /**
  102086. * Gets the frame time capture status
  102087. */
  102088. get: function () {
  102089. return this._captureFrameTime;
  102090. },
  102091. /**
  102092. * Enable or disable the frame time capture
  102093. */
  102094. set: function (value) {
  102095. this._captureFrameTime = value;
  102096. },
  102097. enumerable: true,
  102098. configurable: true
  102099. });
  102100. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  102101. /**
  102102. * Gets the perf counter used for inter-frames time capture
  102103. */
  102104. get: function () {
  102105. return this._interFrameTime;
  102106. },
  102107. enumerable: true,
  102108. configurable: true
  102109. });
  102110. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  102111. /**
  102112. * Gets the inter-frames time capture status
  102113. */
  102114. get: function () {
  102115. return this._captureInterFrameTime;
  102116. },
  102117. /**
  102118. * Enable or disable the inter-frames time capture
  102119. */
  102120. set: function (value) {
  102121. this._captureInterFrameTime = value;
  102122. },
  102123. enumerable: true,
  102124. configurable: true
  102125. });
  102126. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  102127. /**
  102128. * Gets the perf counter used for render time capture
  102129. */
  102130. get: function () {
  102131. return this._renderTime;
  102132. },
  102133. enumerable: true,
  102134. configurable: true
  102135. });
  102136. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  102137. /**
  102138. * Gets the render time capture status
  102139. */
  102140. get: function () {
  102141. return this._captureRenderTime;
  102142. },
  102143. /**
  102144. * Enable or disable the render time capture
  102145. */
  102146. set: function (value) {
  102147. var _this = this;
  102148. if (value === this._captureRenderTime) {
  102149. return;
  102150. }
  102151. this._captureRenderTime = value;
  102152. if (value) {
  102153. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  102154. _this._renderTime.beginMonitoring();
  102155. BABYLON.Tools.StartPerformanceCounter("Main render");
  102156. });
  102157. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  102158. _this._renderTime.endMonitoring(false);
  102159. BABYLON.Tools.EndPerformanceCounter("Main render");
  102160. });
  102161. }
  102162. else {
  102163. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102164. this._onBeforeDrawPhaseObserver = null;
  102165. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102166. this._onAfterDrawPhaseObserver = null;
  102167. }
  102168. },
  102169. enumerable: true,
  102170. configurable: true
  102171. });
  102172. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  102173. /**
  102174. * Gets the perf counter used for camera render time capture
  102175. */
  102176. get: function () {
  102177. return this._cameraRenderTime;
  102178. },
  102179. enumerable: true,
  102180. configurable: true
  102181. });
  102182. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  102183. /**
  102184. * Gets the camera render time capture status
  102185. */
  102186. get: function () {
  102187. return this._captureCameraRenderTime;
  102188. },
  102189. /**
  102190. * Enable or disable the camera render time capture
  102191. */
  102192. set: function (value) {
  102193. var _this = this;
  102194. if (value === this._captureCameraRenderTime) {
  102195. return;
  102196. }
  102197. this._captureCameraRenderTime = value;
  102198. if (value) {
  102199. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  102200. _this._cameraRenderTime.beginMonitoring();
  102201. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  102202. });
  102203. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  102204. _this._cameraRenderTime.endMonitoring(false);
  102205. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  102206. });
  102207. }
  102208. else {
  102209. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102210. this._onBeforeCameraRenderObserver = null;
  102211. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102212. this._onAfterCameraRenderObserver = null;
  102213. }
  102214. },
  102215. enumerable: true,
  102216. configurable: true
  102217. });
  102218. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  102219. /**
  102220. * Gets the perf counter used for draw calls
  102221. */
  102222. get: function () {
  102223. return this.scene.getEngine()._drawCalls;
  102224. },
  102225. enumerable: true,
  102226. configurable: true
  102227. });
  102228. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  102229. /**
  102230. * Gets the perf counter used for texture collisions
  102231. */
  102232. get: function () {
  102233. return this.scene.getEngine()._textureCollisions;
  102234. },
  102235. enumerable: true,
  102236. configurable: true
  102237. });
  102238. SceneInstrumentation.prototype.dispose = function () {
  102239. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  102240. this._onAfterRenderObserver = null;
  102241. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  102242. this._onBeforeActiveMeshesEvaluationObserver = null;
  102243. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  102244. this._onAfterActiveMeshesEvaluationObserver = null;
  102245. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  102246. this._onBeforeRenderTargetsRenderObserver = null;
  102247. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  102248. this._onAfterRenderTargetsRenderObserver = null;
  102249. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  102250. this._onBeforeAnimationsObserver = null;
  102251. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  102252. this._onBeforeParticlesRenderingObserver = null;
  102253. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  102254. this._onAfterParticlesRenderingObserver = null;
  102255. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  102256. this._onBeforeSpritesRenderingObserver = null;
  102257. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  102258. this._onAfterSpritesRenderingObserver = null;
  102259. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  102260. this._onBeforeDrawPhaseObserver = null;
  102261. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  102262. this._onAfterDrawPhaseObserver = null;
  102263. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  102264. this._onBeforePhysicsObserver = null;
  102265. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  102266. this._onAfterPhysicsObserver = null;
  102267. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  102268. this._onAfterAnimationsObserver = null;
  102269. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  102270. this._onBeforeCameraRenderObserver = null;
  102271. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  102272. this._onAfterCameraRenderObserver = null;
  102273. this.scene = null;
  102274. };
  102275. return SceneInstrumentation;
  102276. }());
  102277. BABYLON.SceneInstrumentation = SceneInstrumentation;
  102278. })(BABYLON || (BABYLON = {}));
  102279. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  102280. var BABYLON;
  102281. (function (BABYLON) {
  102282. /**
  102283. * @hidden
  102284. **/
  102285. var _TimeToken = /** @class */ (function () {
  102286. function _TimeToken() {
  102287. this._timeElapsedQueryEnded = false;
  102288. }
  102289. return _TimeToken;
  102290. }());
  102291. BABYLON._TimeToken = _TimeToken;
  102292. })(BABYLON || (BABYLON = {}));
  102293. //# sourceMappingURL=babylon.timeToken.js.map
  102294. var BABYLON;
  102295. (function (BABYLON) {
  102296. /**
  102297. * Background material defines definition.
  102298. * @hidden Mainly internal Use
  102299. */
  102300. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  102301. __extends(BackgroundMaterialDefines, _super);
  102302. /**
  102303. * Constructor of the defines.
  102304. */
  102305. function BackgroundMaterialDefines() {
  102306. var _this = _super.call(this) || this;
  102307. /**
  102308. * True if the diffuse texture is in use.
  102309. */
  102310. _this.DIFFUSE = false;
  102311. /**
  102312. * The direct UV channel to use.
  102313. */
  102314. _this.DIFFUSEDIRECTUV = 0;
  102315. /**
  102316. * True if the diffuse texture is in gamma space.
  102317. */
  102318. _this.GAMMADIFFUSE = false;
  102319. /**
  102320. * True if the diffuse texture has opacity in the alpha channel.
  102321. */
  102322. _this.DIFFUSEHASALPHA = false;
  102323. /**
  102324. * True if you want the material to fade to transparent at grazing angle.
  102325. */
  102326. _this.OPACITYFRESNEL = false;
  102327. /**
  102328. * True if an extra blur needs to be added in the reflection.
  102329. */
  102330. _this.REFLECTIONBLUR = false;
  102331. /**
  102332. * True if you want the material to fade to reflection at grazing angle.
  102333. */
  102334. _this.REFLECTIONFRESNEL = false;
  102335. /**
  102336. * True if you want the material to falloff as far as you move away from the scene center.
  102337. */
  102338. _this.REFLECTIONFALLOFF = false;
  102339. /**
  102340. * False if the current Webgl implementation does not support the texture lod extension.
  102341. */
  102342. _this.TEXTURELODSUPPORT = false;
  102343. /**
  102344. * True to ensure the data are premultiplied.
  102345. */
  102346. _this.PREMULTIPLYALPHA = false;
  102347. /**
  102348. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  102349. */
  102350. _this.USERGBCOLOR = false;
  102351. /**
  102352. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  102353. * stays aligned with the desired configuration.
  102354. */
  102355. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  102356. /**
  102357. * True to add noise in order to reduce the banding effect.
  102358. */
  102359. _this.NOISE = false;
  102360. /**
  102361. * is the reflection texture in BGR color scheme?
  102362. * Mainly used to solve a bug in ios10 video tag
  102363. */
  102364. _this.REFLECTIONBGR = false;
  102365. _this.IMAGEPROCESSING = false;
  102366. _this.VIGNETTE = false;
  102367. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  102368. _this.VIGNETTEBLENDMODEOPAQUE = false;
  102369. _this.TONEMAPPING = false;
  102370. _this.CONTRAST = false;
  102371. _this.COLORCURVES = false;
  102372. _this.COLORGRADING = false;
  102373. _this.COLORGRADING3D = false;
  102374. _this.SAMPLER3DGREENDEPTH = false;
  102375. _this.SAMPLER3DBGRMAP = false;
  102376. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  102377. _this.EXPOSURE = false;
  102378. // Reflection.
  102379. _this.REFLECTION = false;
  102380. _this.REFLECTIONMAP_3D = false;
  102381. _this.REFLECTIONMAP_SPHERICAL = false;
  102382. _this.REFLECTIONMAP_PLANAR = false;
  102383. _this.REFLECTIONMAP_CUBIC = false;
  102384. _this.REFLECTIONMAP_PROJECTION = false;
  102385. _this.REFLECTIONMAP_SKYBOX = false;
  102386. _this.REFLECTIONMAP_EXPLICIT = false;
  102387. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102388. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102389. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102390. _this.INVERTCUBICMAP = false;
  102391. _this.REFLECTIONMAP_OPPOSITEZ = false;
  102392. _this.LODINREFLECTIONALPHA = false;
  102393. _this.GAMMAREFLECTION = false;
  102394. _this.RGBDREFLECTION = false;
  102395. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  102396. // Default BJS.
  102397. _this.MAINUV1 = false;
  102398. _this.MAINUV2 = false;
  102399. _this.UV1 = false;
  102400. _this.UV2 = false;
  102401. _this.CLIPPLANE = false;
  102402. _this.POINTSIZE = false;
  102403. _this.FOG = false;
  102404. _this.NORMAL = false;
  102405. _this.NUM_BONE_INFLUENCERS = 0;
  102406. _this.BonesPerMesh = 0;
  102407. _this.INSTANCES = false;
  102408. _this.SHADOWFLOAT = false;
  102409. _this.rebuild();
  102410. return _this;
  102411. }
  102412. return BackgroundMaterialDefines;
  102413. }(BABYLON.MaterialDefines));
  102414. /**
  102415. * Background material used to create an efficient environement around your scene.
  102416. */
  102417. var BackgroundMaterial = /** @class */ (function (_super) {
  102418. __extends(BackgroundMaterial, _super);
  102419. /**
  102420. * Instantiates a Background Material in the given scene
  102421. * @param name The friendly name of the material
  102422. * @param scene The scene to add the material to
  102423. */
  102424. function BackgroundMaterial(name, scene) {
  102425. var _this = _super.call(this, name, scene) || this;
  102426. /**
  102427. * Key light Color (multiply against the environement texture)
  102428. */
  102429. _this.primaryColor = BABYLON.Color3.White();
  102430. _this._primaryColorShadowLevel = 0;
  102431. _this._primaryColorHighlightLevel = 0;
  102432. /**
  102433. * Reflection Texture used in the material.
  102434. * Should be author in a specific way for the best result (refer to the documentation).
  102435. */
  102436. _this.reflectionTexture = null;
  102437. /**
  102438. * Reflection Texture level of blur.
  102439. *
  102440. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  102441. * texture twice.
  102442. */
  102443. _this.reflectionBlur = 0;
  102444. /**
  102445. * Diffuse Texture used in the material.
  102446. * Should be author in a specific way for the best result (refer to the documentation).
  102447. */
  102448. _this.diffuseTexture = null;
  102449. _this._shadowLights = null;
  102450. /**
  102451. * Specify the list of lights casting shadow on the material.
  102452. * All scene shadow lights will be included if null.
  102453. */
  102454. _this.shadowLights = null;
  102455. /**
  102456. * Helps adjusting the shadow to a softer level if required.
  102457. * 0 means black shadows and 1 means no shadows.
  102458. */
  102459. _this.shadowLevel = 0;
  102460. /**
  102461. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  102462. * It is usually zero but might be interesting to modify according to your setup.
  102463. */
  102464. _this.sceneCenter = BABYLON.Vector3.Zero();
  102465. /**
  102466. * This helps specifying that the material is falling off to the sky box at grazing angle.
  102467. * This helps ensuring a nice transition when the camera goes under the ground.
  102468. */
  102469. _this.opacityFresnel = true;
  102470. /**
  102471. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  102472. * This helps adding a mirror texture on the ground.
  102473. */
  102474. _this.reflectionFresnel = false;
  102475. /**
  102476. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  102477. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  102478. */
  102479. _this.reflectionFalloffDistance = 0.0;
  102480. /**
  102481. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  102482. */
  102483. _this.reflectionAmount = 1.0;
  102484. /**
  102485. * This specifies the weight of the reflection at grazing angle.
  102486. */
  102487. _this.reflectionReflectance0 = 0.05;
  102488. /**
  102489. * This specifies the weight of the reflection at a perpendicular point of view.
  102490. */
  102491. _this.reflectionReflectance90 = 0.5;
  102492. /**
  102493. * Helps to directly use the maps channels instead of their level.
  102494. */
  102495. _this.useRGBColor = true;
  102496. /**
  102497. * This helps reducing the banding effect that could occur on the background.
  102498. */
  102499. _this.enableNoise = false;
  102500. _this._fovMultiplier = 1.0;
  102501. /**
  102502. * Enable the FOV adjustment feature controlled by fovMultiplier.
  102503. */
  102504. _this.useEquirectangularFOV = false;
  102505. _this._maxSimultaneousLights = 4;
  102506. /**
  102507. * Number of Simultaneous lights allowed on the material.
  102508. */
  102509. _this.maxSimultaneousLights = 4;
  102510. /**
  102511. * Keep track of the image processing observer to allow dispose and replace.
  102512. */
  102513. _this._imageProcessingObserver = null;
  102514. /**
  102515. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  102516. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  102517. */
  102518. _this.switchToBGR = false;
  102519. // Temp values kept as cache in the material.
  102520. _this._renderTargets = new BABYLON.SmartArray(16);
  102521. _this._reflectionControls = BABYLON.Vector4.Zero();
  102522. _this._white = BABYLON.Color3.White();
  102523. _this._primaryShadowColor = BABYLON.Color3.Black();
  102524. _this._primaryHighlightColor = BABYLON.Color3.Black();
  102525. // Setup the default processing configuration to the scene.
  102526. _this._attachImageProcessingConfiguration(null);
  102527. _this.getRenderTargetTextures = function () {
  102528. _this._renderTargets.reset();
  102529. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  102530. _this._renderTargets.push(_this._diffuseTexture);
  102531. }
  102532. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  102533. _this._renderTargets.push(_this._reflectionTexture);
  102534. }
  102535. return _this._renderTargets;
  102536. };
  102537. return _this;
  102538. }
  102539. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  102540. /**
  102541. * Experimental Internal Use Only.
  102542. *
  102543. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  102544. * This acts as a helper to set the primary color to a more "human friendly" value.
  102545. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  102546. * output color as close as possible from the chosen value.
  102547. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  102548. * part of lighting setup.)
  102549. */
  102550. get: function () {
  102551. return this.__perceptualColor;
  102552. },
  102553. set: function (value) {
  102554. this.__perceptualColor = value;
  102555. this._computePrimaryColorFromPerceptualColor();
  102556. this._markAllSubMeshesAsLightsDirty();
  102557. },
  102558. enumerable: true,
  102559. configurable: true
  102560. });
  102561. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  102562. /**
  102563. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  102564. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  102565. */
  102566. get: function () {
  102567. return this._primaryColorShadowLevel;
  102568. },
  102569. set: function (value) {
  102570. this._primaryColorShadowLevel = value;
  102571. this._computePrimaryColors();
  102572. this._markAllSubMeshesAsLightsDirty();
  102573. },
  102574. enumerable: true,
  102575. configurable: true
  102576. });
  102577. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  102578. /**
  102579. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  102580. * The primary color is used at the level chosen to define what the white area would look.
  102581. */
  102582. get: function () {
  102583. return this._primaryColorHighlightLevel;
  102584. },
  102585. set: function (value) {
  102586. this._primaryColorHighlightLevel = value;
  102587. this._computePrimaryColors();
  102588. this._markAllSubMeshesAsLightsDirty();
  102589. },
  102590. enumerable: true,
  102591. configurable: true
  102592. });
  102593. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  102594. /**
  102595. * Sets the reflection reflectance fresnel values according to the default standard
  102596. * empirically know to work well :-)
  102597. */
  102598. set: function (value) {
  102599. var reflectionWeight = value;
  102600. if (reflectionWeight < 0.5) {
  102601. reflectionWeight = reflectionWeight * 2.0;
  102602. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  102603. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  102604. }
  102605. else {
  102606. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  102607. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  102608. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  102609. }
  102610. },
  102611. enumerable: true,
  102612. configurable: true
  102613. });
  102614. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  102615. /**
  102616. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102617. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  102618. * Recommended to be keep at 1.0 except for special cases.
  102619. */
  102620. get: function () {
  102621. return this._fovMultiplier;
  102622. },
  102623. set: function (value) {
  102624. if (isNaN(value)) {
  102625. value = 1.0;
  102626. }
  102627. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  102628. },
  102629. enumerable: true,
  102630. configurable: true
  102631. });
  102632. /**
  102633. * Attaches a new image processing configuration to the PBR Material.
  102634. * @param configuration (if null the scene configuration will be use)
  102635. */
  102636. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  102637. var _this = this;
  102638. if (configuration === this._imageProcessingConfiguration) {
  102639. return;
  102640. }
  102641. // Detaches observer.
  102642. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102643. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102644. }
  102645. // Pick the scene configuration if needed.
  102646. if (!configuration) {
  102647. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  102648. }
  102649. else {
  102650. this._imageProcessingConfiguration = configuration;
  102651. }
  102652. // Attaches observer.
  102653. if (this._imageProcessingConfiguration) {
  102654. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  102655. _this._computePrimaryColorFromPerceptualColor();
  102656. _this._markAllSubMeshesAsImageProcessingDirty();
  102657. });
  102658. }
  102659. };
  102660. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  102661. /**
  102662. * Gets the image processing configuration used either in this material.
  102663. */
  102664. get: function () {
  102665. return this._imageProcessingConfiguration;
  102666. },
  102667. /**
  102668. * Sets the Default image processing configuration used either in the this material.
  102669. *
  102670. * If sets to null, the scene one is in use.
  102671. */
  102672. set: function (value) {
  102673. this._attachImageProcessingConfiguration(value);
  102674. // Ensure the effect will be rebuilt.
  102675. this._markAllSubMeshesAsTexturesDirty();
  102676. },
  102677. enumerable: true,
  102678. configurable: true
  102679. });
  102680. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  102681. /**
  102682. * Gets wether the color curves effect is enabled.
  102683. */
  102684. get: function () {
  102685. return this.imageProcessingConfiguration.colorCurvesEnabled;
  102686. },
  102687. /**
  102688. * Sets wether the color curves effect is enabled.
  102689. */
  102690. set: function (value) {
  102691. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  102692. },
  102693. enumerable: true,
  102694. configurable: true
  102695. });
  102696. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  102697. /**
  102698. * Gets wether the color grading effect is enabled.
  102699. */
  102700. get: function () {
  102701. return this.imageProcessingConfiguration.colorGradingEnabled;
  102702. },
  102703. /**
  102704. * Gets wether the color grading effect is enabled.
  102705. */
  102706. set: function (value) {
  102707. this.imageProcessingConfiguration.colorGradingEnabled = value;
  102708. },
  102709. enumerable: true,
  102710. configurable: true
  102711. });
  102712. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  102713. /**
  102714. * Gets wether tonemapping is enabled or not.
  102715. */
  102716. get: function () {
  102717. return this._imageProcessingConfiguration.toneMappingEnabled;
  102718. },
  102719. /**
  102720. * Sets wether tonemapping is enabled or not
  102721. */
  102722. set: function (value) {
  102723. this._imageProcessingConfiguration.toneMappingEnabled = value;
  102724. },
  102725. enumerable: true,
  102726. configurable: true
  102727. });
  102728. ;
  102729. ;
  102730. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  102731. /**
  102732. * The camera exposure used on this material.
  102733. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102734. * This corresponds to a photographic exposure.
  102735. */
  102736. get: function () {
  102737. return this._imageProcessingConfiguration.exposure;
  102738. },
  102739. /**
  102740. * The camera exposure used on this material.
  102741. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  102742. * This corresponds to a photographic exposure.
  102743. */
  102744. set: function (value) {
  102745. this._imageProcessingConfiguration.exposure = value;
  102746. },
  102747. enumerable: true,
  102748. configurable: true
  102749. });
  102750. ;
  102751. ;
  102752. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  102753. /**
  102754. * Gets The camera contrast used on this material.
  102755. */
  102756. get: function () {
  102757. return this._imageProcessingConfiguration.contrast;
  102758. },
  102759. /**
  102760. * Sets The camera contrast used on this material.
  102761. */
  102762. set: function (value) {
  102763. this._imageProcessingConfiguration.contrast = value;
  102764. },
  102765. enumerable: true,
  102766. configurable: true
  102767. });
  102768. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  102769. /**
  102770. * Gets the Color Grading 2D Lookup Texture.
  102771. */
  102772. get: function () {
  102773. return this._imageProcessingConfiguration.colorGradingTexture;
  102774. },
  102775. /**
  102776. * Sets the Color Grading 2D Lookup Texture.
  102777. */
  102778. set: function (value) {
  102779. this.imageProcessingConfiguration.colorGradingTexture = value;
  102780. },
  102781. enumerable: true,
  102782. configurable: true
  102783. });
  102784. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  102785. /**
  102786. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102787. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102788. * 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;
  102789. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102790. */
  102791. get: function () {
  102792. return this.imageProcessingConfiguration.colorCurves;
  102793. },
  102794. /**
  102795. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  102796. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  102797. * 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;
  102798. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  102799. */
  102800. set: function (value) {
  102801. this.imageProcessingConfiguration.colorCurves = value;
  102802. },
  102803. enumerable: true,
  102804. configurable: true
  102805. });
  102806. /**
  102807. * The entire material has been created in order to prevent overdraw.
  102808. * @returns false
  102809. */
  102810. BackgroundMaterial.prototype.needAlphaTesting = function () {
  102811. return true;
  102812. };
  102813. /**
  102814. * The entire material has been created in order to prevent overdraw.
  102815. * @returns true if blending is enable
  102816. */
  102817. BackgroundMaterial.prototype.needAlphaBlending = function () {
  102818. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  102819. };
  102820. /**
  102821. * Checks wether the material is ready to be rendered for a given mesh.
  102822. * @param mesh The mesh to render
  102823. * @param subMesh The submesh to check against
  102824. * @param useInstances Specify wether or not the material is used with instances
  102825. * @returns true if all the dependencies are ready (Textures, Effects...)
  102826. */
  102827. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  102828. var _this = this;
  102829. if (useInstances === void 0) { useInstances = false; }
  102830. if (subMesh.effect && this.isFrozen) {
  102831. if (this._wasPreviouslyReady) {
  102832. return true;
  102833. }
  102834. }
  102835. if (!subMesh._materialDefines) {
  102836. subMesh._materialDefines = new BackgroundMaterialDefines();
  102837. }
  102838. var scene = this.getScene();
  102839. var defines = subMesh._materialDefines;
  102840. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  102841. if (defines._renderId === scene.getRenderId()) {
  102842. return true;
  102843. }
  102844. }
  102845. var engine = scene.getEngine();
  102846. // Lights
  102847. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  102848. defines._needNormals = true;
  102849. // Textures
  102850. if (defines._areTexturesDirty) {
  102851. defines._needUVs = false;
  102852. if (scene.texturesEnabled) {
  102853. if (scene.getEngine().getCaps().textureLOD) {
  102854. defines.TEXTURELODSUPPORT = true;
  102855. }
  102856. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102857. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  102858. return false;
  102859. }
  102860. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  102861. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  102862. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  102863. defines.OPACITYFRESNEL = this._opacityFresnel;
  102864. }
  102865. else {
  102866. defines.DIFFUSE = false;
  102867. defines.DIFFUSEHASALPHA = false;
  102868. defines.GAMMADIFFUSE = false;
  102869. defines.OPACITYFRESNEL = false;
  102870. }
  102871. var reflectionTexture = this._reflectionTexture;
  102872. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102873. if (!reflectionTexture.isReadyOrNotBlocking()) {
  102874. return false;
  102875. }
  102876. defines.REFLECTION = true;
  102877. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  102878. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  102879. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  102880. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  102881. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  102882. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  102883. defines.REFLECTIONBGR = this.switchToBGR;
  102884. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  102885. defines.INVERTCUBICMAP = true;
  102886. }
  102887. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  102888. switch (reflectionTexture.coordinatesMode) {
  102889. case BABYLON.Texture.EXPLICIT_MODE:
  102890. defines.REFLECTIONMAP_EXPLICIT = true;
  102891. break;
  102892. case BABYLON.Texture.PLANAR_MODE:
  102893. defines.REFLECTIONMAP_PLANAR = true;
  102894. break;
  102895. case BABYLON.Texture.PROJECTION_MODE:
  102896. defines.REFLECTIONMAP_PROJECTION = true;
  102897. break;
  102898. case BABYLON.Texture.SKYBOX_MODE:
  102899. defines.REFLECTIONMAP_SKYBOX = true;
  102900. break;
  102901. case BABYLON.Texture.SPHERICAL_MODE:
  102902. defines.REFLECTIONMAP_SPHERICAL = true;
  102903. break;
  102904. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  102905. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  102906. break;
  102907. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  102908. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102909. break;
  102910. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102911. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102912. break;
  102913. case BABYLON.Texture.CUBIC_MODE:
  102914. case BABYLON.Texture.INVCUBIC_MODE:
  102915. default:
  102916. defines.REFLECTIONMAP_CUBIC = true;
  102917. break;
  102918. }
  102919. if (this.reflectionFresnel) {
  102920. defines.REFLECTIONFRESNEL = true;
  102921. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102922. this._reflectionControls.x = this.reflectionAmount;
  102923. this._reflectionControls.y = this.reflectionReflectance0;
  102924. this._reflectionControls.z = this.reflectionReflectance90;
  102925. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102926. }
  102927. else {
  102928. defines.REFLECTIONFRESNEL = false;
  102929. defines.REFLECTIONFALLOFF = false;
  102930. }
  102931. }
  102932. else {
  102933. defines.REFLECTION = false;
  102934. defines.REFLECTIONFRESNEL = false;
  102935. defines.REFLECTIONFALLOFF = false;
  102936. defines.REFLECTIONBLUR = false;
  102937. defines.REFLECTIONMAP_3D = false;
  102938. defines.REFLECTIONMAP_SPHERICAL = false;
  102939. defines.REFLECTIONMAP_PLANAR = false;
  102940. defines.REFLECTIONMAP_CUBIC = false;
  102941. defines.REFLECTIONMAP_PROJECTION = false;
  102942. defines.REFLECTIONMAP_SKYBOX = false;
  102943. defines.REFLECTIONMAP_EXPLICIT = false;
  102944. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102945. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102946. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102947. defines.INVERTCUBICMAP = false;
  102948. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102949. defines.LODINREFLECTIONALPHA = false;
  102950. defines.GAMMAREFLECTION = false;
  102951. defines.RGBDREFLECTION = false;
  102952. }
  102953. }
  102954. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102955. defines.USERGBCOLOR = this._useRGBColor;
  102956. defines.NOISE = this._enableNoise;
  102957. }
  102958. if (defines._areLightsDirty) {
  102959. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102960. }
  102961. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102962. if (!this._imageProcessingConfiguration.isReady()) {
  102963. return false;
  102964. }
  102965. this._imageProcessingConfiguration.prepareDefines(defines);
  102966. }
  102967. // Misc.
  102968. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102969. // Values that need to be evaluated on every frame
  102970. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102971. // Attribs
  102972. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102973. if (mesh) {
  102974. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102975. mesh.createNormals(true);
  102976. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102977. }
  102978. }
  102979. }
  102980. // Get correct effect
  102981. if (defines.isDirty) {
  102982. defines.markAsProcessed();
  102983. scene.resetCachedMaterial();
  102984. // Fallbacks
  102985. var fallbacks = new BABYLON.EffectFallbacks();
  102986. if (defines.FOG) {
  102987. fallbacks.addFallback(0, "FOG");
  102988. }
  102989. if (defines.POINTSIZE) {
  102990. fallbacks.addFallback(1, "POINTSIZE");
  102991. }
  102992. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102993. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102994. fallbacks.addCPUSkinningFallback(0, mesh);
  102995. }
  102996. //Attributes
  102997. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102998. if (defines.NORMAL) {
  102999. attribs.push(BABYLON.VertexBuffer.NormalKind);
  103000. }
  103001. if (defines.UV1) {
  103002. attribs.push(BABYLON.VertexBuffer.UVKind);
  103003. }
  103004. if (defines.UV2) {
  103005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103006. }
  103007. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  103008. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  103009. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  103010. "vFogInfos", "vFogColor", "pointSize",
  103011. "vClipPlane", "mBones",
  103012. "vPrimaryColor", "vPrimaryColorShadow",
  103013. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  103014. "shadowLevel", "alpha",
  103015. "vBackgroundCenter", "vReflectionControl",
  103016. "vDiffuseInfos", "diffuseMatrix",
  103017. ];
  103018. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  103019. var uniformBuffers = ["Material", "Scene"];
  103020. if (BABYLON.ImageProcessingConfiguration) {
  103021. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  103022. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  103023. }
  103024. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  103025. uniformsNames: uniforms,
  103026. uniformBuffersNames: uniformBuffers,
  103027. samplers: samplers,
  103028. defines: defines,
  103029. maxSimultaneousLights: this._maxSimultaneousLights
  103030. });
  103031. var onCompiled = function (effect) {
  103032. if (_this.onCompiled) {
  103033. _this.onCompiled(effect);
  103034. }
  103035. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  103036. };
  103037. var join = defines.toString();
  103038. subMesh.setEffect(scene.getEngine().createEffect("background", {
  103039. attributes: attribs,
  103040. uniformsNames: uniforms,
  103041. uniformBuffersNames: uniformBuffers,
  103042. samplers: samplers,
  103043. defines: join,
  103044. fallbacks: fallbacks,
  103045. onCompiled: onCompiled,
  103046. onError: this.onError,
  103047. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  103048. }, engine), defines);
  103049. this.buildUniformLayout();
  103050. }
  103051. if (!subMesh.effect || !subMesh.effect.isReady()) {
  103052. return false;
  103053. }
  103054. defines._renderId = scene.getRenderId();
  103055. this._wasPreviouslyReady = true;
  103056. return true;
  103057. };
  103058. /**
  103059. * Compute the primary color according to the chosen perceptual color.
  103060. */
  103061. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  103062. if (!this.__perceptualColor) {
  103063. return;
  103064. }
  103065. this._primaryColor.copyFrom(this.__perceptualColor);
  103066. // Revert gamma space.
  103067. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  103068. // Revert image processing configuration.
  103069. if (this._imageProcessingConfiguration) {
  103070. // Revert Exposure.
  103071. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  103072. }
  103073. this._computePrimaryColors();
  103074. };
  103075. /**
  103076. * Compute the highlights and shadow colors according to their chosen levels.
  103077. */
  103078. BackgroundMaterial.prototype._computePrimaryColors = function () {
  103079. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  103080. return;
  103081. }
  103082. // Find the highlight color based on the configuration.
  103083. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  103084. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  103085. // Find the shadow color based on the configuration.
  103086. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  103087. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  103088. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  103089. };
  103090. /**
  103091. * Build the uniform buffer used in the material.
  103092. */
  103093. BackgroundMaterial.prototype.buildUniformLayout = function () {
  103094. // Order is important !
  103095. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  103096. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  103097. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  103098. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  103099. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  103100. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  103101. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  103102. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  103103. this._uniformBuffer.addUniform("pointSize", 1);
  103104. this._uniformBuffer.addUniform("shadowLevel", 1);
  103105. this._uniformBuffer.addUniform("alpha", 1);
  103106. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  103107. this._uniformBuffer.addUniform("vReflectionControl", 4);
  103108. this._uniformBuffer.create();
  103109. };
  103110. /**
  103111. * Unbind the material.
  103112. */
  103113. BackgroundMaterial.prototype.unbind = function () {
  103114. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  103115. this._uniformBuffer.setTexture("diffuseSampler", null);
  103116. }
  103117. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  103118. this._uniformBuffer.setTexture("reflectionSampler", null);
  103119. }
  103120. _super.prototype.unbind.call(this);
  103121. };
  103122. /**
  103123. * Bind only the world matrix to the material.
  103124. * @param world The world matrix to bind.
  103125. */
  103126. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  103127. this._activeEffect.setMatrix("world", world);
  103128. };
  103129. /**
  103130. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  103131. * @param world The world matrix to bind.
  103132. * @param subMesh The submesh to bind for.
  103133. */
  103134. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  103135. var scene = this.getScene();
  103136. var defines = subMesh._materialDefines;
  103137. if (!defines) {
  103138. return;
  103139. }
  103140. var effect = subMesh.effect;
  103141. if (!effect) {
  103142. return;
  103143. }
  103144. this._activeEffect = effect;
  103145. // Matrices
  103146. this.bindOnlyWorldMatrix(world);
  103147. // Bones
  103148. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  103149. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  103150. if (mustRebind) {
  103151. this._uniformBuffer.bindToEffect(effect, "Material");
  103152. this.bindViewProjection(effect);
  103153. var reflectionTexture = this._reflectionTexture;
  103154. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  103155. // Texture uniforms
  103156. if (scene.texturesEnabled) {
  103157. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103158. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  103159. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  103160. }
  103161. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103162. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  103163. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  103164. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  103165. }
  103166. }
  103167. if (this.shadowLevel > 0) {
  103168. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  103169. }
  103170. this._uniformBuffer.updateFloat("alpha", this.alpha);
  103171. // Point size
  103172. if (this.pointsCloud) {
  103173. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  103174. }
  103175. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  103176. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  103177. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  103178. }
  103179. else {
  103180. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  103181. }
  103182. }
  103183. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  103184. // Textures
  103185. if (scene.texturesEnabled) {
  103186. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  103187. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  103188. }
  103189. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  103190. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  103191. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103192. }
  103193. else if (!defines.REFLECTIONBLUR) {
  103194. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  103195. }
  103196. else {
  103197. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  103198. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  103199. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  103200. }
  103201. if (defines.REFLECTIONFRESNEL) {
  103202. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  103203. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  103204. }
  103205. }
  103206. }
  103207. // Clip plane
  103208. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  103209. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  103210. }
  103211. if (mustRebind || !this.isFrozen) {
  103212. if (scene.lightsEnabled) {
  103213. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  103214. }
  103215. // View
  103216. this.bindView(effect);
  103217. // Fog
  103218. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  103219. // image processing
  103220. if (this._imageProcessingConfiguration) {
  103221. this._imageProcessingConfiguration.bind(this._activeEffect);
  103222. }
  103223. }
  103224. this._uniformBuffer.update();
  103225. this._afterBind(mesh, this._activeEffect);
  103226. };
  103227. /**
  103228. * Dispose the material.
  103229. * @param forceDisposeEffect Force disposal of the associated effect.
  103230. * @param forceDisposeTextures Force disposal of the associated textures.
  103231. */
  103232. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  103233. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  103234. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  103235. if (forceDisposeTextures) {
  103236. if (this.diffuseTexture) {
  103237. this.diffuseTexture.dispose();
  103238. }
  103239. if (this.reflectionTexture) {
  103240. this.reflectionTexture.dispose();
  103241. }
  103242. }
  103243. this._renderTargets.dispose();
  103244. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  103245. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  103246. }
  103247. _super.prototype.dispose.call(this, forceDisposeEffect);
  103248. };
  103249. /**
  103250. * Clones the material.
  103251. * @param name The cloned name.
  103252. * @returns The cloned material.
  103253. */
  103254. BackgroundMaterial.prototype.clone = function (name) {
  103255. var _this = this;
  103256. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  103257. };
  103258. /**
  103259. * Serializes the current material to its JSON representation.
  103260. * @returns The JSON representation.
  103261. */
  103262. BackgroundMaterial.prototype.serialize = function () {
  103263. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  103264. serializationObject.customType = "BABYLON.BackgroundMaterial";
  103265. return serializationObject;
  103266. };
  103267. /**
  103268. * Gets the class name of the material
  103269. * @returns "BackgroundMaterial"
  103270. */
  103271. BackgroundMaterial.prototype.getClassName = function () {
  103272. return "BackgroundMaterial";
  103273. };
  103274. /**
  103275. * Parse a JSON input to create back a background material.
  103276. * @param source The JSON data to parse
  103277. * @param scene The scene to create the parsed material in
  103278. * @param rootUrl The root url of the assets the material depends upon
  103279. * @returns the instantiated BackgroundMaterial.
  103280. */
  103281. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  103282. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  103283. };
  103284. /**
  103285. * Standard reflectance value at parallel view angle.
  103286. */
  103287. BackgroundMaterial.StandardReflectance0 = 0.05;
  103288. /**
  103289. * Standard reflectance value at grazing angle.
  103290. */
  103291. BackgroundMaterial.StandardReflectance90 = 0.5;
  103292. __decorate([
  103293. BABYLON.serializeAsColor3()
  103294. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  103295. __decorate([
  103296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103297. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  103298. __decorate([
  103299. BABYLON.serializeAsColor3()
  103300. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  103301. __decorate([
  103302. BABYLON.serialize()
  103303. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  103304. __decorate([
  103305. BABYLON.serialize()
  103306. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  103307. __decorate([
  103308. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  103309. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  103310. __decorate([
  103311. BABYLON.serializeAsTexture()
  103312. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  103313. __decorate([
  103314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103315. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  103316. __decorate([
  103317. BABYLON.serialize()
  103318. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  103319. __decorate([
  103320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103321. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  103322. __decorate([
  103323. BABYLON.serializeAsTexture()
  103324. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  103325. __decorate([
  103326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103327. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  103328. __decorate([
  103329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103330. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  103331. __decorate([
  103332. BABYLON.serialize()
  103333. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  103334. __decorate([
  103335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103336. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  103337. __decorate([
  103338. BABYLON.serializeAsVector3()
  103339. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  103340. __decorate([
  103341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103342. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  103343. __decorate([
  103344. BABYLON.serialize()
  103345. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  103346. __decorate([
  103347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103348. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  103349. __decorate([
  103350. BABYLON.serialize()
  103351. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  103352. __decorate([
  103353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103354. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  103355. __decorate([
  103356. BABYLON.serialize()
  103357. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  103358. __decorate([
  103359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103360. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  103361. __decorate([
  103362. BABYLON.serialize()
  103363. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  103364. __decorate([
  103365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103366. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  103367. __decorate([
  103368. BABYLON.serialize()
  103369. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  103370. __decorate([
  103371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103372. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  103373. __decorate([
  103374. BABYLON.serialize()
  103375. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  103376. __decorate([
  103377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103378. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  103379. __decorate([
  103380. BABYLON.serialize()
  103381. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  103382. __decorate([
  103383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103384. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  103385. __decorate([
  103386. BABYLON.serialize()
  103387. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  103388. __decorate([
  103389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103390. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  103391. __decorate([
  103392. BABYLON.serialize()
  103393. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  103394. __decorate([
  103395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  103396. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  103397. __decorate([
  103398. BABYLON.serializeAsImageProcessingConfiguration()
  103399. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  103400. return BackgroundMaterial;
  103401. }(BABYLON.PushMaterial));
  103402. BABYLON.BackgroundMaterial = BackgroundMaterial;
  103403. })(BABYLON || (BABYLON = {}));
  103404. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  103405. var __assign = (this && this.__assign) || Object.assign || function(t) {
  103406. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103407. s = arguments[i];
  103408. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103409. t[p] = s[p];
  103410. }
  103411. return t;
  103412. };
  103413. var BABYLON;
  103414. (function (BABYLON) {
  103415. /**
  103416. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  103417. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  103418. * It also helps with the default setup of your imageProcessing configuration.
  103419. */
  103420. var EnvironmentHelper = /** @class */ (function () {
  103421. /**
  103422. * constructor
  103423. * @param options
  103424. * @param scene The scene to add the material to
  103425. */
  103426. function EnvironmentHelper(options, scene) {
  103427. var _this = this;
  103428. this._errorHandler = function (message, exception) {
  103429. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  103430. };
  103431. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  103432. this._scene = scene;
  103433. this.onErrorObservable = new BABYLON.Observable();
  103434. this._setupBackground();
  103435. this._setupImageProcessing();
  103436. }
  103437. /**
  103438. * Creates the default options for the helper.
  103439. */
  103440. EnvironmentHelper._getDefaultOptions = function () {
  103441. return {
  103442. createGround: true,
  103443. groundSize: 15,
  103444. groundTexture: this._groundTextureCDNUrl,
  103445. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103446. groundOpacity: 0.9,
  103447. enableGroundShadow: true,
  103448. groundShadowLevel: 0.5,
  103449. enableGroundMirror: false,
  103450. groundMirrorSizeRatio: 0.3,
  103451. groundMirrorBlurKernel: 64,
  103452. groundMirrorAmount: 1,
  103453. groundMirrorFresnelWeight: 1,
  103454. groundMirrorFallOffDistance: 0,
  103455. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  103456. groundYBias: 0.00001,
  103457. createSkybox: true,
  103458. skyboxSize: 20,
  103459. skyboxTexture: this._skyboxTextureCDNUrl,
  103460. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  103461. backgroundYRotation: 0,
  103462. sizeAuto: true,
  103463. rootPosition: BABYLON.Vector3.Zero(),
  103464. setupImageProcessing: true,
  103465. environmentTexture: this._environmentTextureCDNUrl,
  103466. cameraExposure: 0.8,
  103467. cameraContrast: 1.2,
  103468. toneMappingEnabled: true,
  103469. };
  103470. };
  103471. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  103472. /**
  103473. * Gets the root mesh created by the helper.
  103474. */
  103475. get: function () {
  103476. return this._rootMesh;
  103477. },
  103478. enumerable: true,
  103479. configurable: true
  103480. });
  103481. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  103482. /**
  103483. * Gets the skybox created by the helper.
  103484. */
  103485. get: function () {
  103486. return this._skybox;
  103487. },
  103488. enumerable: true,
  103489. configurable: true
  103490. });
  103491. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  103492. /**
  103493. * Gets the skybox texture created by the helper.
  103494. */
  103495. get: function () {
  103496. return this._skyboxTexture;
  103497. },
  103498. enumerable: true,
  103499. configurable: true
  103500. });
  103501. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  103502. /**
  103503. * Gets the skybox material created by the helper.
  103504. */
  103505. get: function () {
  103506. return this._skyboxMaterial;
  103507. },
  103508. enumerable: true,
  103509. configurable: true
  103510. });
  103511. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  103512. /**
  103513. * Gets the ground mesh created by the helper.
  103514. */
  103515. get: function () {
  103516. return this._ground;
  103517. },
  103518. enumerable: true,
  103519. configurable: true
  103520. });
  103521. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  103522. /**
  103523. * Gets the ground texture created by the helper.
  103524. */
  103525. get: function () {
  103526. return this._groundTexture;
  103527. },
  103528. enumerable: true,
  103529. configurable: true
  103530. });
  103531. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  103532. /**
  103533. * Gets the ground mirror created by the helper.
  103534. */
  103535. get: function () {
  103536. return this._groundMirror;
  103537. },
  103538. enumerable: true,
  103539. configurable: true
  103540. });
  103541. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  103542. /**
  103543. * Gets the ground mirror render list to helps pushing the meshes
  103544. * you wish in the ground reflection.
  103545. */
  103546. get: function () {
  103547. if (this._groundMirror) {
  103548. return this._groundMirror.renderList;
  103549. }
  103550. return null;
  103551. },
  103552. enumerable: true,
  103553. configurable: true
  103554. });
  103555. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  103556. /**
  103557. * Gets the ground material created by the helper.
  103558. */
  103559. get: function () {
  103560. return this._groundMaterial;
  103561. },
  103562. enumerable: true,
  103563. configurable: true
  103564. });
  103565. /**
  103566. * Updates the background according to the new options
  103567. * @param options
  103568. */
  103569. EnvironmentHelper.prototype.updateOptions = function (options) {
  103570. var newOptions = __assign({}, this._options, options);
  103571. if (this._ground && !newOptions.createGround) {
  103572. this._ground.dispose();
  103573. this._ground = null;
  103574. }
  103575. if (this._groundMaterial && !newOptions.createGround) {
  103576. this._groundMaterial.dispose();
  103577. this._groundMaterial = null;
  103578. }
  103579. if (this._groundTexture) {
  103580. if (this._options.groundTexture != newOptions.groundTexture) {
  103581. this._groundTexture.dispose();
  103582. this._groundTexture = null;
  103583. }
  103584. }
  103585. if (this._skybox && !newOptions.createSkybox) {
  103586. this._skybox.dispose();
  103587. this._skybox = null;
  103588. }
  103589. if (this._skyboxMaterial && !newOptions.createSkybox) {
  103590. this._skyboxMaterial.dispose();
  103591. this._skyboxMaterial = null;
  103592. }
  103593. if (this._skyboxTexture) {
  103594. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  103595. this._skyboxTexture.dispose();
  103596. this._skyboxTexture = null;
  103597. }
  103598. }
  103599. if (this._groundMirror && !newOptions.enableGroundMirror) {
  103600. this._groundMirror.dispose();
  103601. this._groundMirror = null;
  103602. }
  103603. if (this._scene.environmentTexture) {
  103604. if (this._options.environmentTexture != newOptions.environmentTexture) {
  103605. this._scene.environmentTexture.dispose();
  103606. }
  103607. }
  103608. this._options = newOptions;
  103609. this._setupBackground();
  103610. this._setupImageProcessing();
  103611. };
  103612. /**
  103613. * Sets the primary color of all the available elements.
  103614. * @param color the main color to affect to the ground and the background
  103615. */
  103616. EnvironmentHelper.prototype.setMainColor = function (color) {
  103617. if (this.groundMaterial) {
  103618. this.groundMaterial.primaryColor = color;
  103619. }
  103620. if (this.skyboxMaterial) {
  103621. this.skyboxMaterial.primaryColor = color;
  103622. }
  103623. if (this.groundMirror) {
  103624. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  103625. }
  103626. };
  103627. /**
  103628. * Setup the image processing according to the specified options.
  103629. */
  103630. EnvironmentHelper.prototype._setupImageProcessing = function () {
  103631. if (this._options.setupImageProcessing) {
  103632. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  103633. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  103634. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  103635. this._setupEnvironmentTexture();
  103636. }
  103637. };
  103638. /**
  103639. * Setup the environment texture according to the specified options.
  103640. */
  103641. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  103642. if (this._scene.environmentTexture) {
  103643. return;
  103644. }
  103645. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  103646. this._scene.environmentTexture = this._options.environmentTexture;
  103647. return;
  103648. }
  103649. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  103650. this._scene.environmentTexture = environmentTexture;
  103651. };
  103652. /**
  103653. * Setup the background according to the specified options.
  103654. */
  103655. EnvironmentHelper.prototype._setupBackground = function () {
  103656. if (!this._rootMesh) {
  103657. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  103658. }
  103659. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  103660. var sceneSize = this._getSceneSize();
  103661. if (this._options.createGround) {
  103662. this._setupGround(sceneSize);
  103663. this._setupGroundMaterial();
  103664. this._setupGroundDiffuseTexture();
  103665. if (this._options.enableGroundMirror) {
  103666. this._setupGroundMirrorTexture(sceneSize);
  103667. }
  103668. this._setupMirrorInGroundMaterial();
  103669. }
  103670. if (this._options.createSkybox) {
  103671. this._setupSkybox(sceneSize);
  103672. this._setupSkyboxMaterial();
  103673. this._setupSkyboxReflectionTexture();
  103674. }
  103675. this._rootMesh.position.x = sceneSize.rootPosition.x;
  103676. this._rootMesh.position.z = sceneSize.rootPosition.z;
  103677. this._rootMesh.position.y = sceneSize.rootPosition.y;
  103678. };
  103679. /**
  103680. * Get the scene sizes according to the setup.
  103681. */
  103682. EnvironmentHelper.prototype._getSceneSize = function () {
  103683. var _this = this;
  103684. var groundSize = this._options.groundSize;
  103685. var skyboxSize = this._options.skyboxSize;
  103686. var rootPosition = this._options.rootPosition;
  103687. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  103688. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103689. }
  103690. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  103691. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  103692. });
  103693. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  103694. if (this._options.sizeAuto) {
  103695. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  103696. this._scene.activeCamera.upperRadiusLimit) {
  103697. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  103698. skyboxSize = groundSize;
  103699. }
  103700. var sceneDiagonalLenght = sceneDiagonal.length();
  103701. if (sceneDiagonalLenght > groundSize) {
  103702. groundSize = sceneDiagonalLenght * 2;
  103703. skyboxSize = groundSize;
  103704. }
  103705. // 10 % bigger.
  103706. groundSize *= 1.1;
  103707. skyboxSize *= 1.5;
  103708. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  103709. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  103710. }
  103711. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  103712. };
  103713. /**
  103714. * Setup the ground according to the specified options.
  103715. */
  103716. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  103717. var _this = this;
  103718. if (!this._ground || this._ground.isDisposed()) {
  103719. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  103720. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  103721. this._ground.parent = this._rootMesh;
  103722. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  103723. }
  103724. this._ground.receiveShadows = this._options.enableGroundShadow;
  103725. };
  103726. /**
  103727. * Setup the ground material according to the specified options.
  103728. */
  103729. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  103730. if (!this._groundMaterial) {
  103731. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  103732. }
  103733. this._groundMaterial.alpha = this._options.groundOpacity;
  103734. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  103735. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  103736. this._groundMaterial.primaryColor = this._options.groundColor;
  103737. this._groundMaterial.useRGBColor = false;
  103738. this._groundMaterial.enableNoise = true;
  103739. if (this._ground) {
  103740. this._ground.material = this._groundMaterial;
  103741. }
  103742. };
  103743. /**
  103744. * Setup the ground diffuse texture according to the specified options.
  103745. */
  103746. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  103747. if (!this._groundMaterial) {
  103748. return;
  103749. }
  103750. if (this._groundTexture) {
  103751. return;
  103752. }
  103753. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  103754. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  103755. return;
  103756. }
  103757. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103758. diffuseTexture.gammaSpace = false;
  103759. diffuseTexture.hasAlpha = true;
  103760. this._groundMaterial.diffuseTexture = diffuseTexture;
  103761. };
  103762. /**
  103763. * Setup the ground mirror texture according to the specified options.
  103764. */
  103765. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  103766. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103767. if (!this._groundMirror) {
  103768. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  103769. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  103770. this._groundMirror.anisotropicFilteringLevel = 1;
  103771. this._groundMirror.wrapU = wrapping;
  103772. this._groundMirror.wrapV = wrapping;
  103773. this._groundMirror.gammaSpace = false;
  103774. if (this._groundMirror.renderList) {
  103775. for (var i = 0; i < this._scene.meshes.length; i++) {
  103776. var mesh = this._scene.meshes[i];
  103777. if (mesh !== this._ground &&
  103778. mesh !== this._skybox &&
  103779. mesh !== this._rootMesh) {
  103780. this._groundMirror.renderList.push(mesh);
  103781. }
  103782. }
  103783. }
  103784. }
  103785. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  103786. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  103787. };
  103788. /**
  103789. * Setup the ground to receive the mirror texture.
  103790. */
  103791. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  103792. if (this._groundMaterial) {
  103793. this._groundMaterial.reflectionTexture = this._groundMirror;
  103794. this._groundMaterial.reflectionFresnel = true;
  103795. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  103796. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  103797. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  103798. }
  103799. };
  103800. /**
  103801. * Setup the skybox according to the specified options.
  103802. */
  103803. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  103804. var _this = this;
  103805. if (!this._skybox || this._skybox.isDisposed()) {
  103806. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  103807. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  103808. }
  103809. this._skybox.parent = this._rootMesh;
  103810. };
  103811. /**
  103812. * Setup the skybox material according to the specified options.
  103813. */
  103814. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  103815. if (!this._skybox) {
  103816. return;
  103817. }
  103818. if (!this._skyboxMaterial) {
  103819. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  103820. }
  103821. this._skyboxMaterial.useRGBColor = false;
  103822. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  103823. this._skyboxMaterial.enableNoise = true;
  103824. this._skybox.material = this._skyboxMaterial;
  103825. };
  103826. /**
  103827. * Setup the skybox reflection texture according to the specified options.
  103828. */
  103829. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  103830. if (!this._skyboxMaterial) {
  103831. return;
  103832. }
  103833. if (this._skyboxTexture) {
  103834. return;
  103835. }
  103836. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  103837. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  103838. return;
  103839. }
  103840. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  103841. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  103842. this._skyboxTexture.gammaSpace = false;
  103843. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  103844. };
  103845. /**
  103846. * Dispose all the elements created by the Helper.
  103847. */
  103848. EnvironmentHelper.prototype.dispose = function () {
  103849. if (this._groundMaterial) {
  103850. this._groundMaterial.dispose(true, true);
  103851. }
  103852. if (this._skyboxMaterial) {
  103853. this._skyboxMaterial.dispose(true, true);
  103854. }
  103855. this._rootMesh.dispose(false);
  103856. };
  103857. /**
  103858. * Default ground texture URL.
  103859. */
  103860. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  103861. /**
  103862. * Default skybox texture URL.
  103863. */
  103864. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  103865. /**
  103866. * Default environment texture URL.
  103867. */
  103868. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  103869. return EnvironmentHelper;
  103870. }());
  103871. BABYLON.EnvironmentHelper = EnvironmentHelper;
  103872. })(BABYLON || (BABYLON = {}));
  103873. //# sourceMappingURL=babylon.environmentHelper.js.map
  103874. var BABYLON;
  103875. (function (BABYLON) {
  103876. /** Internal class used to store shapes for emitters */
  103877. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  103878. function ParticleSystemSetEmitterCreationOptions() {
  103879. }
  103880. return ParticleSystemSetEmitterCreationOptions;
  103881. }());
  103882. /**
  103883. * Represents a set of particle systems working together to create a specific effect
  103884. */
  103885. var ParticleSystemSet = /** @class */ (function () {
  103886. function ParticleSystemSet() {
  103887. /**
  103888. * Gets the particle system list
  103889. */
  103890. this.systems = new Array();
  103891. }
  103892. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  103893. /**
  103894. * Gets the emitter node used with this set
  103895. */
  103896. get: function () {
  103897. return this._emitterNode;
  103898. },
  103899. enumerable: true,
  103900. configurable: true
  103901. });
  103902. /**
  103903. * Creates a new emitter mesh as a sphere
  103904. * @param options defines the options used to create the sphere
  103905. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  103906. * @param scene defines the hosting scene
  103907. */
  103908. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103909. if (this._emitterNode) {
  103910. this._emitterNode.dispose();
  103911. }
  103912. this._emitterCreationOptions = {
  103913. kind: "Sphere",
  103914. options: options,
  103915. renderingGroupId: renderingGroupId
  103916. };
  103917. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103918. emitterMesh.renderingGroupId = renderingGroupId;
  103919. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103920. material.emissiveColor = options.color;
  103921. emitterMesh.material = material;
  103922. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103923. var system = _a[_i];
  103924. system.emitter = emitterMesh;
  103925. }
  103926. this._emitterNode = emitterMesh;
  103927. };
  103928. /**
  103929. * Starts all particle systems of the set
  103930. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103931. */
  103932. ParticleSystemSet.prototype.start = function (emitter) {
  103933. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103934. var system = _a[_i];
  103935. if (emitter) {
  103936. system.emitter = emitter;
  103937. }
  103938. system.start();
  103939. }
  103940. };
  103941. /**
  103942. * Release all associated resources
  103943. */
  103944. ParticleSystemSet.prototype.dispose = function () {
  103945. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103946. var system = _a[_i];
  103947. system.dispose();
  103948. }
  103949. this.systems = [];
  103950. if (this._emitterNode) {
  103951. this._emitterNode.dispose();
  103952. this._emitterNode = null;
  103953. }
  103954. };
  103955. /**
  103956. * Serialize the set into a JSON compatible object
  103957. * @returns a JSON compatible representation of the set
  103958. */
  103959. ParticleSystemSet.prototype.serialize = function () {
  103960. var result = {};
  103961. result.systems = [];
  103962. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103963. var system = _a[_i];
  103964. result.systems.push(system.serialize());
  103965. }
  103966. if (this._emitterNode) {
  103967. result.emitter = this._emitterCreationOptions;
  103968. }
  103969. return result;
  103970. };
  103971. /**
  103972. * Parse a new ParticleSystemSet from a serialized source
  103973. * @param data defines a JSON compatible representation of the set
  103974. * @param scene defines the hosting scene
  103975. * @param gpu defines if we want GPU particles or CPU particles
  103976. * @returns a new ParticleSystemSet
  103977. */
  103978. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103979. if (gpu === void 0) { gpu = false; }
  103980. var result = new ParticleSystemSet();
  103981. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103982. scene = scene || BABYLON.Engine.LastCreatedScene;
  103983. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103984. var system = _a[_i];
  103985. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103986. }
  103987. if (data.emitter) {
  103988. var options = data.emitter.options;
  103989. switch (data.emitter.kind) {
  103990. case "Sphere":
  103991. result.setEmitterAsSphere({
  103992. diameter: options.diameter,
  103993. segments: options.segments,
  103994. color: BABYLON.Color3.FromArray(options.color)
  103995. }, data.emitter.renderingGroupId, scene);
  103996. break;
  103997. }
  103998. }
  103999. return result;
  104000. };
  104001. return ParticleSystemSet;
  104002. }());
  104003. BABYLON.ParticleSystemSet = ParticleSystemSet;
  104004. })(BABYLON || (BABYLON = {}));
  104005. //# sourceMappingURL=babylon.particleSystemSet.js.map
  104006. var BABYLON;
  104007. (function (BABYLON) {
  104008. /**
  104009. * This class is made for on one-liner static method to help creating particle system set.
  104010. */
  104011. var ParticleHelper = /** @class */ (function () {
  104012. function ParticleHelper() {
  104013. }
  104014. /**
  104015. * This is the main static method (one-liner) of this helper to create different particle systems
  104016. * @param type This string represents the type to the particle system to create
  104017. * @param scene The scene where the particle system should live
  104018. * @param gpu If the system will use gpu
  104019. * @returns the ParticleSystemSet created
  104020. */
  104021. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  104022. if (gpu === void 0) { gpu = false; }
  104023. if (!scene) {
  104024. scene = BABYLON.Engine.LastCreatedScene;
  104025. ;
  104026. }
  104027. var token = {};
  104028. scene._addPendingData(token);
  104029. return new Promise(function (resolve, reject) {
  104030. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  104031. scene._removePendingData(token);
  104032. return reject("Particle system with GPU is not supported.");
  104033. }
  104034. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  104035. scene._removePendingData(token);
  104036. var newData = JSON.parse(data.toString());
  104037. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  104038. }, undefined, undefined, undefined, function (req, exception) {
  104039. scene._removePendingData(token);
  104040. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  104041. });
  104042. });
  104043. };
  104044. /**
  104045. * Static function used to export a particle system to a ParticleSystemSet variable.
  104046. * Please note that the emitter shape is not exported
  104047. * @param system defines the particle systems to export
  104048. */
  104049. ParticleHelper.ExportSet = function (systems) {
  104050. var set = new BABYLON.ParticleSystemSet();
  104051. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  104052. var system = systems_1[_i];
  104053. set.systems.push(system);
  104054. }
  104055. return set;
  104056. };
  104057. /**
  104058. * Gets or sets base Assets URL
  104059. */
  104060. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  104061. return ParticleHelper;
  104062. }());
  104063. BABYLON.ParticleHelper = ParticleHelper;
  104064. })(BABYLON || (BABYLON = {}));
  104065. //# sourceMappingURL=babylon.particleHelper.js.map
  104066. var BABYLON;
  104067. (function (BABYLON) {
  104068. /**
  104069. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  104070. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  104071. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  104072. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104073. */
  104074. var VideoDome = /** @class */ (function (_super) {
  104075. __extends(VideoDome, _super);
  104076. /**
  104077. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  104078. * @param name Element's name, child elements will append suffixes for their own names.
  104079. * @param urlsOrVideo defines the url(s) or the video element to use
  104080. * @param options An object containing optional or exposed sub element properties
  104081. */
  104082. function VideoDome(name, urlsOrVideo, options, scene) {
  104083. var _this = _super.call(this, name, scene) || this;
  104084. _this._useDirectMapping = false;
  104085. // set defaults and manage values
  104086. name = name || "videoDome";
  104087. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104088. options.clickToPlay = Boolean(options.clickToPlay);
  104089. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  104090. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  104091. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104092. if (options.useDirectMapping === undefined) {
  104093. _this._useDirectMapping = true;
  104094. }
  104095. else {
  104096. _this._useDirectMapping = options.useDirectMapping;
  104097. }
  104098. _this._setReady(false);
  104099. // create
  104100. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  104101. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104102. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  104103. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104104. texture.onLoadObservable.addOnce(function () {
  104105. _this._setReady(true);
  104106. });
  104107. // configure material
  104108. material.useEquirectangularFOV = true;
  104109. material.fovMultiplier = 1.0;
  104110. material.opacityFresnel = false;
  104111. if (_this._useDirectMapping) {
  104112. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104113. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104114. material.diffuseTexture = texture;
  104115. }
  104116. else {
  104117. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104118. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104119. material.reflectionTexture = texture;
  104120. }
  104121. // configure mesh
  104122. _this._mesh.material = material;
  104123. _this._mesh.parent = _this;
  104124. // optional configuration
  104125. if (options.clickToPlay) {
  104126. scene.onPointerUp = function () {
  104127. _this._videoTexture.video.play();
  104128. };
  104129. }
  104130. return _this;
  104131. }
  104132. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  104133. /**
  104134. * Gets the video texture being displayed on the sphere
  104135. */
  104136. get: function () {
  104137. return this._videoTexture;
  104138. },
  104139. enumerable: true,
  104140. configurable: true
  104141. });
  104142. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  104143. /**
  104144. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104145. * Also see the options.resolution property.
  104146. */
  104147. get: function () {
  104148. return this._material.fovMultiplier;
  104149. },
  104150. set: function (value) {
  104151. this._material.fovMultiplier = value;
  104152. },
  104153. enumerable: true,
  104154. configurable: true
  104155. });
  104156. /**
  104157. * Releases resources associated with this node.
  104158. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104159. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104160. */
  104161. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104162. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104163. this._videoTexture.dispose();
  104164. this._mesh.dispose();
  104165. this._material.dispose();
  104166. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104167. };
  104168. return VideoDome;
  104169. }(BABYLON.Node));
  104170. BABYLON.VideoDome = VideoDome;
  104171. })(BABYLON || (BABYLON = {}));
  104172. //# sourceMappingURL=babylon.videoDome.js.map
  104173. var BABYLON;
  104174. (function (BABYLON) {
  104175. /**
  104176. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  104177. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  104178. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  104179. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  104180. */
  104181. var PhotoDome = /** @class */ (function (_super) {
  104182. __extends(PhotoDome, _super);
  104183. /**
  104184. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  104185. * @param name Element's name, child elements will append suffixes for their own names.
  104186. * @param urlsOfPhoto define the url of the photo to display
  104187. * @param options An object containing optional or exposed sub element properties
  104188. */
  104189. function PhotoDome(name, urlOfPhoto, options, scene) {
  104190. var _this = _super.call(this, name, scene) || this;
  104191. _this._useDirectMapping = false;
  104192. // set defaults and manage values
  104193. name = name || "photoDome";
  104194. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  104195. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  104196. if (options.useDirectMapping === undefined) {
  104197. _this._useDirectMapping = true;
  104198. }
  104199. else {
  104200. _this._useDirectMapping = options.useDirectMapping;
  104201. }
  104202. _this._setReady(false);
  104203. // create
  104204. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  104205. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  104206. // configure material
  104207. material.opacityFresnel = false;
  104208. material.useEquirectangularFOV = true;
  104209. material.fovMultiplier = 1.0;
  104210. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  104211. _this.photoTexture.onLoadObservable.addOnce(function () {
  104212. _this._setReady(true);
  104213. });
  104214. // configure mesh
  104215. _this._mesh.material = material;
  104216. _this._mesh.parent = _this;
  104217. return _this;
  104218. }
  104219. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  104220. /**
  104221. * Gets or sets the texture being displayed on the sphere
  104222. */
  104223. get: function () {
  104224. return this._photoTexture;
  104225. },
  104226. set: function (value) {
  104227. if (this._photoTexture === value) {
  104228. return;
  104229. }
  104230. this._photoTexture = value;
  104231. if (this._useDirectMapping) {
  104232. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104233. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104234. this._material.diffuseTexture = this._photoTexture;
  104235. }
  104236. else {
  104237. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  104238. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104239. this._material.reflectionTexture = this._photoTexture;
  104240. }
  104241. },
  104242. enumerable: true,
  104243. configurable: true
  104244. });
  104245. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  104246. /**
  104247. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104248. * Also see the options.resolution property.
  104249. */
  104250. get: function () {
  104251. return this._material.fovMultiplier;
  104252. },
  104253. set: function (value) {
  104254. this._material.fovMultiplier = value;
  104255. },
  104256. enumerable: true,
  104257. configurable: true
  104258. });
  104259. /**
  104260. * Releases resources associated with this node.
  104261. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  104262. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  104263. */
  104264. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  104265. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  104266. this._photoTexture.dispose();
  104267. this._mesh.dispose();
  104268. this._material.dispose();
  104269. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  104270. };
  104271. return PhotoDome;
  104272. }(BABYLON.Node));
  104273. BABYLON.PhotoDome = PhotoDome;
  104274. })(BABYLON || (BABYLON = {}));
  104275. //# sourceMappingURL=babylon.photoDome.js.map
  104276. var BABYLON;
  104277. (function (BABYLON) {
  104278. BABYLON.Engine.prototype.createQuery = function () {
  104279. return this._gl.createQuery();
  104280. };
  104281. BABYLON.Engine.prototype.deleteQuery = function (query) {
  104282. this._gl.deleteQuery(query);
  104283. return this;
  104284. };
  104285. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  104286. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  104287. };
  104288. BABYLON.Engine.prototype.getQueryResult = function (query) {
  104289. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  104290. };
  104291. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  104292. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104293. this._gl.beginQuery(glAlgorithm, query);
  104294. return this;
  104295. };
  104296. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  104297. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  104298. this._gl.endQuery(glAlgorithm);
  104299. return this;
  104300. };
  104301. BABYLON.Engine.prototype._createTimeQuery = function () {
  104302. var timerQuery = this.getCaps().timerQuery;
  104303. if (timerQuery.createQueryEXT) {
  104304. return timerQuery.createQueryEXT();
  104305. }
  104306. return this.createQuery();
  104307. };
  104308. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  104309. var timerQuery = this.getCaps().timerQuery;
  104310. if (timerQuery.deleteQueryEXT) {
  104311. timerQuery.deleteQueryEXT(query);
  104312. return;
  104313. }
  104314. this.deleteQuery(query);
  104315. };
  104316. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  104317. var timerQuery = this.getCaps().timerQuery;
  104318. if (timerQuery.getQueryObjectEXT) {
  104319. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  104320. }
  104321. return this.getQueryResult(query);
  104322. };
  104323. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  104324. var timerQuery = this.getCaps().timerQuery;
  104325. if (timerQuery.getQueryObjectEXT) {
  104326. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  104327. }
  104328. return this.isQueryResultAvailable(query);
  104329. };
  104330. BABYLON.Engine.prototype.startTimeQuery = function () {
  104331. var caps = this.getCaps();
  104332. var timerQuery = caps.timerQuery;
  104333. if (!timerQuery) {
  104334. return null;
  104335. }
  104336. var token = new BABYLON._TimeToken();
  104337. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104338. if (caps.canUseTimestampForTimerQuery) {
  104339. token._startTimeQuery = this._createTimeQuery();
  104340. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  104341. }
  104342. else {
  104343. if (this._currentNonTimestampToken) {
  104344. return this._currentNonTimestampToken;
  104345. }
  104346. token._timeElapsedQuery = this._createTimeQuery();
  104347. if (timerQuery.beginQueryEXT) {
  104348. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104349. }
  104350. else {
  104351. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  104352. }
  104353. this._currentNonTimestampToken = token;
  104354. }
  104355. return token;
  104356. };
  104357. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  104358. var caps = this.getCaps();
  104359. var timerQuery = caps.timerQuery;
  104360. if (!timerQuery || !token) {
  104361. return -1;
  104362. }
  104363. if (caps.canUseTimestampForTimerQuery) {
  104364. if (!token._startTimeQuery) {
  104365. return -1;
  104366. }
  104367. if (!token._endTimeQuery) {
  104368. token._endTimeQuery = this._createTimeQuery();
  104369. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  104370. }
  104371. }
  104372. else if (!token._timeElapsedQueryEnded) {
  104373. if (!token._timeElapsedQuery) {
  104374. return -1;
  104375. }
  104376. if (timerQuery.endQueryEXT) {
  104377. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  104378. }
  104379. else {
  104380. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  104381. }
  104382. token._timeElapsedQueryEnded = true;
  104383. }
  104384. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  104385. var available = false;
  104386. if (token._endTimeQuery) {
  104387. available = this._getTimeQueryAvailability(token._endTimeQuery);
  104388. }
  104389. else if (token._timeElapsedQuery) {
  104390. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  104391. }
  104392. if (available && !disjoint) {
  104393. var result = 0;
  104394. if (caps.canUseTimestampForTimerQuery) {
  104395. if (!token._startTimeQuery || !token._endTimeQuery) {
  104396. return -1;
  104397. }
  104398. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  104399. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  104400. result = timeEnd - timeStart;
  104401. this._deleteTimeQuery(token._startTimeQuery);
  104402. this._deleteTimeQuery(token._endTimeQuery);
  104403. token._startTimeQuery = null;
  104404. token._endTimeQuery = null;
  104405. }
  104406. else {
  104407. if (!token._timeElapsedQuery) {
  104408. return -1;
  104409. }
  104410. result = this._getTimeQueryResult(token._timeElapsedQuery);
  104411. this._deleteTimeQuery(token._timeElapsedQuery);
  104412. token._timeElapsedQuery = null;
  104413. token._timeElapsedQueryEnded = false;
  104414. this._currentNonTimestampToken = null;
  104415. }
  104416. return result;
  104417. }
  104418. return -1;
  104419. };
  104420. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  104421. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  104422. };
  104423. // We also need to update AbstractMesh as there is a portion of the code there
  104424. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  104425. var engine = this.getEngine();
  104426. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  104427. this._isOccluded = false;
  104428. return;
  104429. }
  104430. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  104431. this._isOccluded = false;
  104432. return;
  104433. }
  104434. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  104435. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  104436. if (isOcclusionQueryAvailable) {
  104437. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  104438. this._isOcclusionQueryInProgress = false;
  104439. this._occlusionInternalRetryCounter = 0;
  104440. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  104441. }
  104442. else {
  104443. this._occlusionInternalRetryCounter++;
  104444. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  104445. this._isOcclusionQueryInProgress = false;
  104446. this._occlusionInternalRetryCounter = 0;
  104447. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  104448. // if strict continue the last state of the object.
  104449. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  104450. }
  104451. else {
  104452. return;
  104453. }
  104454. }
  104455. }
  104456. var scene = this.getScene();
  104457. if (scene.getBoundingBoxRenderer) {
  104458. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  104459. if (!this._occlusionQuery) {
  104460. this._occlusionQuery = engine.createQuery();
  104461. }
  104462. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  104463. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  104464. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  104465. this._isOcclusionQueryInProgress = true;
  104466. }
  104467. };
  104468. })(BABYLON || (BABYLON = {}));
  104469. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  104470. var BABYLON;
  104471. (function (BABYLON) {
  104472. /**
  104473. * Class used to generate noise procedural textures
  104474. */
  104475. var NoiseProceduralTexture = /** @class */ (function (_super) {
  104476. __extends(NoiseProceduralTexture, _super);
  104477. /**
  104478. * Creates a new NoiseProceduralTexture
  104479. * @param name defines the name fo the texture
  104480. * @param size defines the size of the texture (default is 256)
  104481. * @param scene defines the hosting scene
  104482. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  104483. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  104484. */
  104485. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  104486. if (size === void 0) { size = 256; }
  104487. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  104488. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  104489. _this._time = 0;
  104490. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  104491. _this.brightness = 0.2;
  104492. /** Defines the number of octaves to process */
  104493. _this.octaves = 3;
  104494. /** Defines the level of persistence (0.8 by default) */
  104495. _this.persistence = 0.8;
  104496. /** Gets or sets animation speed factor (default is 1) */
  104497. _this.animationSpeedFactor = 1;
  104498. _this._updateShaderUniforms();
  104499. return _this;
  104500. }
  104501. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  104502. var scene = this.getScene();
  104503. if (!scene) {
  104504. return;
  104505. }
  104506. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  104507. this.setFloat("brightness", this.brightness);
  104508. this.setInt("octaves", this.octaves);
  104509. this.setFloat("persistence", this.persistence);
  104510. this.setFloat("timeScale", this._time);
  104511. };
  104512. /** Generate the current state of the procedural texture */
  104513. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  104514. this._updateShaderUniforms();
  104515. _super.prototype.render.call(this, useCameraPostProcess);
  104516. };
  104517. /**
  104518. * Serializes this noise procedural texture
  104519. * @returns a serialized noise procedural texture object
  104520. */
  104521. NoiseProceduralTexture.prototype.serialize = function () {
  104522. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  104523. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  104524. return serializationObject;
  104525. };
  104526. /**
  104527. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  104528. * @param parsedTexture defines parsed texture data
  104529. * @param scene defines the current scene
  104530. * @param rootUrl defines the root URL containing noise procedural texture information
  104531. * @returns a parsed NoiseProceduralTexture
  104532. */
  104533. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  104534. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  104535. return texture;
  104536. };
  104537. return NoiseProceduralTexture;
  104538. }(BABYLON.ProceduralTexture));
  104539. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  104540. })(BABYLON || (BABYLON = {}));
  104541. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  104542. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\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 BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform int octaves;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<octaves; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  104543. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  104544. globalObject["BABYLON"] = BABYLON;
  104545. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var ColorGradient = BABYLON.ColorGradient;var FactorGradient = BABYLON.FactorGradient;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var SceneComponentConstants = BABYLON.SceneComponentConstants;var Stage = BABYLON.Stage;var AbstractScene = BABYLON.AbstractScene;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var StringDictionary = BABYLON.StringDictionary;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RawCubeTexture = BABYLON.RawCubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcessManager = BABYLON.PostProcessManager;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var GamepadSystemSceneComponent = BABYLON.GamepadSystemSceneComponent;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystemSceneComponent = BABYLON.LensFlareSystemSceneComponent;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var DDSTools = BABYLON.DDSTools;var TGATools = BABYLON.TGATools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var EnvironmentTextureTools = BABYLON.EnvironmentTextureTools;var UtilityLayerRenderer = BABYLON.UtilityLayerRenderer;var PointerDragBehavior = BABYLON.PointerDragBehavior;var MultiPointerScaleBehavior = BABYLON.MultiPointerScaleBehavior;var SixDofDragBehavior = BABYLON.SixDofDragBehavior;var AttachToBoxBehavior = BABYLON.AttachToBoxBehavior;var Gizmo = BABYLON.Gizmo;var AxisDragGizmo = BABYLON.AxisDragGizmo;var AxisScaleGizmo = BABYLON.AxisScaleGizmo;var PlaneRotationGizmo = BABYLON.PlaneRotationGizmo;var PositionGizmo = BABYLON.PositionGizmo;var RotationGizmo = BABYLON.RotationGizmo;var ScaleGizmo = BABYLON.ScaleGizmo;var BoundingBoxGizmo = BABYLON.BoundingBoxGizmo;var GizmoManager = BABYLON.GizmoManager;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayerSceneComponent = BABYLON.EffectLayerSceneComponent;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var LayerSceneComponent = BABYLON.LayerSceneComponent;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var ParticleSystemSet = BABYLON.ParticleSystemSet;var ParticleHelper = BABYLON.ParticleHelper;var VideoDome = BABYLON.VideoDome;var PhotoDome = BABYLON.PhotoDome;var NoiseProceduralTexture = BABYLON.NoiseProceduralTexture;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Debug = BABYLON.Debug ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  104546. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,ColorGradient,FactorGradient,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,SceneComponentConstants,Stage,AbstractScene,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PerformanceMonitor,RollingAverage,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,StringDictionary,RayHelper,DebugLayer,BoundingBoxRenderer,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RawCubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcessManager,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,GamepadSystemSceneComponent,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,HDRTools,HDRCubeTexture,PanoramaToCubeMapTools,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystemSceneComponent,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,DDSTools,TGATools,KhronosTextureContainer,EnvironmentTextureTools,UtilityLayerRenderer,PointerDragBehavior,MultiPointerScaleBehavior,SixDofDragBehavior,AttachToBoxBehavior,Gizmo,AxisDragGizmo,AxisScaleGizmo,PlaneRotationGizmo,PositionGizmo,RotationGizmo,ScaleGizmo,BoundingBoxGizmo,GizmoManager,MorphTarget,MorphTargetManager,Octree,OctreeBlock,AnaglyphPostProcess,AnaglyphArcRotateCamera,AnaglyphFreeCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicInterlacePostProcess,StereoscopicArcRotateCamera,StereoscopicFreeCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRDistortionCorrectionPostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationArcRotateCamera,VRDeviceOrientationGamepadCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayerSceneComponent,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,LayerSceneComponent,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,ParticleSystemSet,ParticleHelper,VideoDome,PhotoDome,NoiseProceduralTexture,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Debug ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };